Redux - how to tell the difference between unloaded content and content that doesn't exist in the back-end?

Viewed 77

In a redux store, for example if I store customers data as:

{
  data: [1, 2, 3],
  customers: {
    1: { ... },
    2: { ... },
    3: { ... }
  }
}

In a component, when I try to display customer with id 4, seeing that this customer doesn't exist in the store, I would attempt to fetch this customer using an API call. Now, assume that customer 4 in fact doesn't exist in the back-end database. At the end of the API call, the store is updated and customer 4 is still not in the store.

My question is, from the component, this doesn't tell me whether the customer has not been loaded (in that case I will need to load again), or that the customer in fact does not exist in the back-end database (in that case I will need to display an appropriate message). How is this usually handled in Redux?

2 Answers

You may want to add error field to the redux store. When making the API call update the error if no customer found in DB.

{
  data: [1, 2, 3],
  customers: {
    1: { ... },
    2: { ... },
    3: { ... }
  },
  error: null,
}
// api.js
fetch("backend-url.com/customer/4")
  .then(res => res.json)
  .then(result => {
    // don't forget to clear the error in the reducer
    dispatch(addCustomer(result));
  })
  .catch(err => {
    // No customer found
    dispatch(storeError(err));
  });

Then in component

// component.js

...

const { customers, data, error } = useReduxStore();

return (
  <div>
    { error ? <Error message={error} /> : <Customers customers={customers} /> }
  </div>
); 

You could check in your component after loading a customer, if the customer is an empty object {} ... then it's loaded but doesn't exist, and if it's null ... then you need to fire a redux action to load it...

- If you got an error ... then you might display a generic error message like Something went wrong which might be an internet-connect issue, or an internal issue in your backend

export const getCustomer = () => dispatch => {
  dispatch({ type: 'GET_CUSTOMER_START' });

  axios
    .get('your api end point')
    .then(res => {
      const customer = res.data;

      dispatch({
        type: 'GET_CUSTOMER_SUCCESS',
        payload: {
          customer: customer || {},
        },
      });
    })
    .catch(error => {
      dispatch({
        type: 'GET_CUSTOMER_FAIL',
        payload: { error },
      });
    });
};
Related