2

I have the following state and reducer but it's not pushing in the new array object.

const initialState = {
    photos: [],
    selectedPhoto:{},
    photosTeamId:'',
    photosProjectId:''
};

case actionTypes.PHOTOS_UPDATE:
            return Object.assign({}, state, {
                photos:action.data.photos,
                photosTeamId:action.data.photosTeamId,
                photosProjectId:action.data.photosProjectId
            })

photos is not getting pushed but overwritten

Almog
  • 2,639
  • 6
  • 30
  • 59
  • See this https://stackoverflow.com/questions/43376849/use-object-assign-or-spread-operator-in-react-redux-which-is-a-better-practise/43376980#43376980 and this https://stackoverflow.com/questions/41949387/how-to-use-immutability-helper-to-update-a-nested-object-within-an-array/41949486#41949486. You can either go with Spread operator syntax or Immutability-helper package – Shubham Khatri Nov 02 '17 at 08:12

3 Answers3

2

Here's a more cleaner way using javascript spread syntax:

const initialState = {
    photos: [],
    selectedPhoto:{},
    photosTeamId:'',
    photosProjectId:''
};

case actionTypes.PHOTOS_UPDATE:
            return {
                ...state,
                photos: [...state.photos, ...actions.data.photos],
                photosTeamId: action.data.photosTeamId,
                photosProjectId: action.data.photosProjectId
            }
Shubhnik Singh
  • 1,329
  • 10
  • 13
0
case actionTypes.PHOTOS_UPDATE:
  return {
    ...state,
    photos: state.photos.concat(action.data.photos),
    photosTeamId: action.data.photosTeamId,
    photosProjectId: action.data.photosProjectId
  };
vinayr
  • 11,026
  • 3
  • 46
  • 42
0

Here's the spread operator […]. The spread operator can be used to take an existing array and add another element to it while still preserving the original array.

Example:

case actionTypes.PHOTOS_UPDATE:
  return [
    ...state,
    Object.assign({}, {
      photos:action.data.photos,
      photosTeamId:action.data.photosTeamId,
      photosProjectId:action.data.photosProjectId
    })
  ];
vikram jeet singh
  • 3,416
  • 2
  • 21
  • 22