Search code examples
javascriptreactjsreduxredux-thunk

Saving data to redux vs making API calls to backend


So I have an app that relies on redux-thunk and an express backend. Would it be considered good practice to fetch data and make a post request at the same time?

Here is a code example:

export const getProducts = () => async (dispatch) => {
  const { data } = await API.getProducts();
  dispatch({ type: 'GET_PRODUCTS', payload: data });
};

export const createProduct = (proData) => async (dispatch) => {
  const { data, status } = await API.createProduct(proData);
  if (status === 200) {
    dispatch(getProducts());
  }
};

Solution

  • Yes that is fine for most cases.

    You could also consider returning the new product in the response from your express api and adding it to redux after createProduct finishes like:

    export const createProduct = (proData) => async (dispatch) => {
      const { data, status } = await API.createProduct(proData);
      if (status === 200) {
        // add product to state
        dispatch(productCreated(data));
      }
    };
    

    A more advanced option would be to optimistically update your store (and UI) by dispatching an event before the request finishes.

    export const createProduct = (proData) => async (dispatch) => {
      dispatch(productCreatedPending(proData));
      const { data, status } = await API.createProduct(proData);
      if (status !== 200) {
        // Handle error by dispatching another action to fix the state
        // or however you want
      }
    };
    

    Depends how you want your UI to work