Home > Mobile >  How to spread state into a specific array
How to spread state into a specific array

Time:05-09

I've got an array of objects and when a certain functions called I want to update a specific array within that array of objects with new data.

Heres the call:

const DataReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_DATA':
      return [...state, state[0].data:[...state, {id: Math.floor(Math.random() * 999),
        name: action.payload.name,
   }]];
  }
}

The problem is I keep getting an error "',' Expected", this appears on the : after data I'm pretty sure this is correct though, I'm using the context api to update some existing state with new names when the addName function is called. This should spread the existing state and take the specific state from item[0].data, adding the new name to it but I cant seem to get it working.

Any help would be appreciated.

Here's the original data object: [{title: 'Names', data: []}, {title: 'Meal', data: []}]

CodePudding user response:

return [
  { 
    ...(state[0] || {}),
    data: {
      id: Math.floor(Math.random() * 999),
      name: payload.name
    } 
  },
  ...state?.slice?.(1)
]

CodePudding user response:

It might be easier to break up that return. Make a copy of the state, create an object, and add that to the data array, preserving any objects that are already in there. Then return the copy to update the state.

const DataReducer = (state, action) => {

 const { type, payload } = action; 

 switch (type) {

    case 'ADD_DATA': {

      const copy = [...state];

      copy[0].data = {
        ...copy[0], 
        data: [
          ...copy[0].data, {
            id: Math.floor(Math.random() * 999),
            name: 'Bob'
          }
        ]
      };

      return copy;

    }
  }
}

const state = [{title: 'Names', data: []}, {title: 'Meal', data: []}];

const newState = DataReducer(state, { type: 'ADD_DATA', payload: { name: 'Bob' } });

console.log(newState);

  • Related