I am new to redux so apologies if it's a stupid question. I have a react application and I am adding redux store to it. I am using thunk
middleware to execute async code to get/save data from the backend.
I have this below in index.js
:
store.dispatch(loadInitialState());
loadInitialState()
calls backend service and loads the initial data and dispatches an action to load initial state:
dispatch({
type: LOAD_INITIAL_STATE,
payload: initData,
});
Now, in case things didn't go well I dispatch a set error action like this:
dispatch({ type: SET_ERROR_MESSAGE, payload: errorMessage });
and the reducer has got this:
case actions.SET_ERROR_MESSAGE:
return {
...state,
error: action.payload,
};
case actions.RESET_ERROR_MESSAGE:
return {
...state,
error: null,
};
I have a component called <DisplayError />
that I have included in App.js
at the top where on every page of the application this component will be first one to render and it uses useSelector(state => state.error)
to find if there and an error to display it.
The problem: If I have an error on a route/page and if I navigate away from that route the error message stays there because that component it common at the top of all pages. The only way I see to solve this is to do dispatch({ type: RESET_ERROR_MESSAGE, payload: null });
everywhere in the application to make sure that error message doesn't appear where it's not supposed to.
What is the way to reset error that set in redux state?