erikthedeveloper / listapp-reactjs-redux-example

An example App built with React and Redux that reads and writes from a JSON API
1 stars 0 forks source link

Redux-ify ListApp #7

Open erikthedeveloper opened 8 years ago

erikthedeveloper commented 8 years ago

Beginning w/ the fully functional ListApp built only with React, introduce Redux and refactor applicable state/logic/actions out of components and into Redux

erikthedeveloper commented 8 years ago

One possibility...

scratch_28_-_react_listapp_-____projects_fun_react_listapp_
/**
 * Async action to update an "item"
 * @param id
 * @param data Payload for PATCH "/items/:id"
 * @return {Function} redux-thunk
 */
function updateItem(id, data) {
  /** @return {Promise} */
  return (dispatch) => {
    // Async: Start (use for "loading" UI)
    dispatch(updateItemAsync(id));

    return httpClient.patch(`/items/${id}`, data)
      // Async: Success (Update itemsReducer.items[{id}] and stop "loading")
      .then((res) => {
        const updatedItem = res.body.item;
        dispatch(updateItemSuccess(id, updatedItem))
      })
      // Async: Fail (Update itemsReducer.errors[{id}] and stop "loading")
      .catch((err) => {
        const validationErrors = err.res.errors;
        dispatch(updateItemFail(id, validationErrors));
      });
  };
}

function updateItemAsync(id) {
  return {
    type: 'UPDATE_ITEM_ASYNC',
    id,
  };
}

function updateItemSuccess(id, updatedItem) {
  return {
    type: 'UPDATE_ITEM_SUCCESS',
    id,
    item: updatedItem,
  };
}

function updateItemFail(id, errors) {
  return {
    type: 'UPDATE_ITEM_FAIL',
    id,
    errors,
  };
}