0

I am using ES6 spread operator in my react-redux app like this way

var defaultState = {val:1, items:[]};
export default function(state=defaultState, action){
  switch(action.type){
    case 'ADD_BOOK':
    state.val = 0;
    return {
      ...state,
      items:action.payload.data.result
    };

The problem is each time I get fresh data from action.payload.data.result assigned to items. I want to have concatenated data from previous state. Can someone help.

h_h
  • 1,201
  • 4
  • 28
  • 47

2 Answers2

2

This should work.

return {
  ...state,
  items: [
    ...state.items,
    ...aciton.payload.data.result
  ]
}
Rafael Berro
  • 2,518
  • 1
  • 17
  • 24
1

so what you really need to do here, is concat the existing items and those returned from your payload.

Assuming this is the case, then you need to create a new array from the old items array and new. You also want to avoid mutating the existing state.

Return a completely new state from your reducer. Do this by cloning the existing state and adding your new items array:

case 'ADD_BOOK':
    var newState = Object.assign({}, state, {val:0}); // clones the existing state and adds our new val
    newState.items = newState.Items.concat(action.payload.data.result);
    return newState;

There are cleaner ways to do this with the spread syntax or libraries such as immutable but this example will explicitly achieve what we need to do.

hairmot
  • 2,975
  • 1
  • 13
  • 26