Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to spread state into a specific array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help would be appreciated.

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading