Search code examples
reactjsreduxstateecmascript-next

How to update a react redux state with object spread properly?


I have a user state saved in localStorage that looks like this after authentication:

  "user" : {
  "first_name":"test19", 
  "last_name":"test19",
  "email":"test19@testmail.com",
  "token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjcyMCwia"
   ...

Now I also have a form that triggers an action to update the user's state once the server returned the updated info and my reducer looks like this:

case userConstants.UPDATE_USER:
      return {
        loggedIn: true,
        ...state,
        user: action.user
      };

So far so good except that the returned object from the server doesn't include a token, and the result of the reducer above is a new state without the token which I need.

Any ideas what I'm doing wrong? thanks! :)


Solution

  • If I understand your question correctly, you want to avoid losing the token after an update. Update your reducer like this.

    case userConstants.UPDATE_USER:
        return {
            loggedIn: true,
            ...state,
            user: {
                ...action.user,
                token: state.user.token
            }
        };
    

    The idea here is that, you will override the token attribute of the action.user with the one in the state(without mutating), before returning the new state.