0

I have a state of type array that initially looks like that:

const initialState = {
    spots: []
}

On the first update it gets filled with objects and looks like that:

state.spots = [
    { id: '1', available: 1, path: 'xxx' },
    { id: '2', available: 1, path: 'xxz' },
    { id: '3', available: 1, path: 'xxy' },
    { id: '4', available: 1, path: 'bxy' },
    { id: '5', available: 1, path: 'vxy' },
    { id: '6', available: 1, path: 'fxy' }
]

On all subsequent updates we get all the spots with keys of 'id' and 'available' but not the path.

So the payload looks like this:

payload = [
    { id: '1', available: 1 },
    { id: '2', available: 0 },
    { id: '3', available: 0 },
    { id: '4', available: 1 },
    { id: '5', available: 0 },
    { id: '6', available: 1 }
]

I'm trying to figure out the immutable ES6 pattern to update the state but I cannot seem to get it right.

EDIT: Best solution I have found so far is the following:

state.spots = state.spots.map( (spot, key) => {    
  let new_spot = payload.find(o => o.id === spot.id);
  return { ...spot, ...new_spot }
})

What is the most efficient way to properly update all objects of the array "spots" with the new payload.

Hope it is clear. Thanks

ion
  • 1,033
  • 2
  • 16
  • 46
  • Seems like it would be easier if the payload and state were objects with id as key and the rest as value. Is that an option? – vinkomlacic Jul 02 '19 at 14:32

1 Answers1

0

CodeSandbox


You can create a hash map of your payload using each spot's id as the key:

const payload = [
    { id: '1', available: 1 },
    { id: '2', available: 0 },
    { id: '3', available: 0 },
    { id: '4', available: 1 },
    { id: '5', available: 0 },
    { id: '6', available: 1 }
]

// You can adjust the map to how you like.

const map = payload.reduce((acc, entry) => {
    acc[entry.id] = entry
    return acc
}, {})

and then update state.spots in your reducer:

return {
    ...state,

    spots: state.spots.map(e => {
        if (map[e.id]) return { ...e, ...map[e.id] };
        return e;
    })
};
khan
  • 1,466
  • 8
  • 19