Home > other >  Adding items into array inside object without mutating state
Adding items into array inside object without mutating state

Time:08-26

For reference this is the initial state:

const initialState = {
  dogs: [],
  cats: [],
  petToPreview: {},
  petToAdopt: {},
};

I have the following case that I am trying to solve

case 'ADD_NEW_DOG':
      let pleaseWork = {
        ...state,
        dogs: [action.dog],
      };
      console.log(pleaseWork);

The action creator I am using is this:

export const addNewDog = (pet) => {
  return {
    type: 'ADD_NEW_DOG',
    dog: pet,
  };
};

The question I am trying to solve is that this case adds the new dog to the end of the dogs array (without mutating the previous state). The way that I have it set up right now, is that it adds the action correctly, However, every time a new 'dog' tries to get added, it just overwrites the previous one.

When I log out my case I get this:

{
  dogs: [ { id: 1, name: 'Taylor' } ],
  cats: [],
  petToPreview: {},
  petToAdopt: {}
}

However, Like I mentioned any new action that gets added, overwrites this. I have tried pushing into the 'clone' however this I know mutates the array, so I do not know where to go from here.

CodePudding user response:

You need to clone dogs array and add new entry at the end.

case 'ADD_NEW_DOG':
      let pleaseWork = {
        ...state,
        dogs: [...state.dogs, action.dog],
      };
      console.log(pleaseWork);

CodePudding user response:

You replace the new array with the older one,

case 'ADD_NEW_DOG':
      let pleaseWork = {
        ...state,
        dogs: [...state.dogs,action.dog],

};

  • Related