Last Updated: September 02, 2016
·
306
· byronsm

Avoid State Manipulation in Actions

Avoid the urge to manipulate state in your actions. You are more likely to run into race conditions. Actions are not guaranteed to resolve in order.

// BAD!!!
export const UPDATE_INBOX = 'UPDATE_INBOX';
export const readMail = (mail) => (dispatch, getState, { api }) => {
   // optimistically update all mail to read
  const read = mail.map((letter) => (
    { ...letter, read_at: letter.read_at || new Date() }
  ));
  dispatch({ type: UPDATE_INBOX, mail: read });

// GOOD!!!
export const READ_MAIL = 'READ_MAIL';
export const readMail = () => (dispatch, getState, { api }) => {
   // optimistically update all mail to read
  dispatch({ type: READ_MAIL });

// mail reducer
switch (action.type) {
  case READ_MAIL:
    return state.map(m => ({ ...m, read_at: m.read_at || new Date() }));

Leverage the syncronous nature of the store to avoid zombie state.