Skip to content Skip to sidebar Skip to footer

How To Change Nested Object Without Mutating It In Redux

I am pretty new guy to redux.I am little bit confused that how to change this data without mutating it. my data structure like this { postOwnwerName:'', postTags:

Solution 1:

if the state object has many level it will be difficult to change state without mutating. In those scenario I first copy the state deeply and then make changes to the new state and return new state. See here Cloning object deeply. You can try this once.

export default function uploadReducer(state=initialState,action) {
  let newState = JSON.parse(JSON.stringify(state));
  switch (action.type){
    case types.SETPHOTOSTATE:
       newState.photos.push(action.payload);
       return newState;
    case types.SETCAPTIONTEXT:
       newState.photos.map((data) => {
         if(data.id == action.payload.id){
           data.caption = action.payload.caption;
         }
       });
       return newState;
   default:
     return newState;
   }
}

Post a Comment for "How To Change Nested Object Without Mutating It In Redux"