Search code examples
javascriptreactjsredux

How to save objects from an array of objects individually in Redux?


I try to send to my Redux state an array of objects and I try to save it in my state.

Redux State:

savedEvents: [],

My array of elements I try to send looks like: [{1},{2}]

My dispatch method :

case 'events/setNewEvent': 
            return { ...state, savedEvents: [...state.savedEvents, action.payload] }; 

If I try to use this 'case', my 'savedEvents' will look like [[{1},{2}]] ant not like [{1},{2}]. Both will be on index 0.

What I have to change in my code to be saved individually, and not together?


Solution

  • You just have to spread the new events in with the ... operator:

    return { ...state, savedEvents: [...state.savedEvents, ...action.payload] };