reducer - update the complete state

62 views Asked by At

I want to add a case to the reducer where i want to set the complete state , not any specific attributes.

updating specific attributes[SET_SELECTED_PAGE,UPDATE_MESSAGE_DISPLAYED] are working fine. But when i try SET_INIT_DATA i get error Parsing error: Unexpected token, expected ",".The payload for SET_INIT_DATA will have complete json.

My state will be like

{
  "user": "",
  "selectedPage": "home",
  "message": "Message from admin",
  ...
}

Code:

 const reducer = (state, action) => {
      switch (action.type) {
        case "SET_SELECTED_PAGE":
          return {
             ...state,
            selectedPage: action.payload 
          };
        case "UPDATE_MESSAGE_DISPLAYED":
          return {
              ...state,
              messageDisplayed: action.payload 
            };
      case "SET_INIT_DATA":
          return {
              action.payload // getting error Parsing error: Unexpected token, expected ","
           }; 
        default:
          throw new Error();
      }
    };
1

There are 1 answers

2
AudioBubble On BEST ANSWER

It should probably be:

      case "SET_INIT_DATA":
          return action.payload;

Yours didn't work because it's a syntax error. JS object initialization requires either a key, value pair (or object property short form), or the spread operator. You provided neither so it's a syntax error.

Since action.payload is a suitable object it qualifies fine to return from a reducer, with no need to create a wrapper object since you want the object as it is.