'How to handle api responses and notification when using Redux store?

Whenever I perform an action, I would like to check the API response before displaying a success message. for example, below I have this function to delete the item and I call it using react-redux dispatch

dispatch(deleteItemID(itemId));
notify.show("Home Id is successfully added", "success", 3000);

the problem here, is dispatch, doesn't return anything directly. so I am not sure if the response status is 200 or 400. the deleteItemID then call async function removeItem" see bellow function.

export const deleteItemID = (itemId) => {
  return (dispatch, getState) => {
    removeItem(itemId);
    const state = getState().main;
    state.items = state.items.filter(
      (item) => item.Key !== itemId
    );
  };
};

Now I am confused, I could add something like

.then((resp) => {
      if (resp) {
        dispatch({ type: "GET_ACCOUNT_DETAILS_DATA", data: resp });
      }
    });

inside deleteItemID, but by the time the state update it will be too late because notify.show() runs just after the dispatch.

I am not sure where that kind of error/success should be displayed message. should I use Notifications inside my API services? does not sound like a good practice. inside redux? I am really confused if someone could help me understand the proper of redux



Solution 1:[1]

Depending how you've built your store, you can use 2 options, both involving middleware.

The first is outlined here. Its pretty deep dive into how this works, and shows you how to manually write out your own async action, and what middleware is commonly used (i.e redux-thunk, redux-saga, etc).

The second is using @redux/toolkit. This reduces the boilerplate code needed. And simplifies your life, by being able to call one function called createAsyncThunk. This documentation is found here. As a quick note, it gives your reducer three states to track, the pending, failed, and fulfilled states, where pending is loading, failed is when the async request fails, and fulfilled when it returns a valid response. You can use this to show a success, waiting, or error message.

The reason either of these must be done, is because redux action dispatches are synchronous by design. Async actions must therefore, be sent to middleware FIRST, as async actions contain side effects, which Redux reducers should never have, but middleware will handle and then dispatch a synchronous action when the promise resolves.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1