Search code examples
javascriptreactjsreduxreact-reduxreact-router-dom

How to reset values of react-redux?


I've been using the MERN stack.
I want to know how to reset values in redux values.
If I send incorrect data to backend /login route and I get 'Invalid email or password' and I save it redux. I see that in the front-end. When changing the route and after I change the route to the login (react) page I see this message. If I refresh the page redux reset.
I have a question how to reset value without refresh and change route?


Solution

  • If i am understanding it correctly then your problem is that after one dispatch (api call with redux) your redux state gets some data and when you dispatches another time then you are getting previously stored redux value, Just like the situation in which i am currently.

    When i have logged out then then my redux got a value "logout successfully" and without refreshing the browser i am logging in then i am getting 2x "logout succesfully".

    Here is a simple way to avoid this :-

    step 1 :- create another reducer case after your previous ones and just clear them when your desired work completed.

    .addCase('clearRedux', (state) => {
        state.error = null;
        state.message = null;
    });
    

    step 2:- select the reducer in which you want to perform action

    const { message: logoutMessage, error: logoutError } = useSelector((state)=>state.logoutWorker);
    

    step 3 :- dispatch the case when its needed

    useEffect(() => {
        if (logoutMessage) {
          alert.success(logoutMessage);
          dispatch(loadWorker());
          dispatch({
            type: 'clearRedux'
          });
        }
    
        if (logoutError) {
            alert.error(logoutMessage);
            dispatch({
                type: 'clearRedux'
            });
        }
    }, [dispatch, logoutMessage, logoutError]);
    

    I hope your error will get resolved have a great coding day #eat_sleep_code_repeat.