Aashay Amballi
Aashay Amballi

Reputation: 1431

Updating a list of objects in a list of objects immutably

I have a requirement that from Axios call I'll be getting a list of objects which need to be updated in the redux store.

For example, consider I have an initial state like this.

const initialState = {

someData: [

  {
    id: 1,
    data: 'some data',
    ...
    chosen: true,
    user:'Joe'
  },
  {
    id: 2,
    data: 'some data',
    ...
    chosen: false,
    user:null
  },
  {
    id: 3,
    data: 'some data',
    ...
    chosen: false,
    user:null
  },
  {
    id: 4,
    data: 'some data',
    ...
    chosen: true,
    user:'Jacob'
  },
  {
    id: 5,
    data: 'some data',
    ...
    chosen: false,
    user:null
  }

]

}


and from Axios call, I'll get a list of objects which need to be updated in the store.

sample data of a received list of objects :

[

  {
    id: 2,
    data: 'some data',
    ...
    chosen: true,
    user:'Jake'
  },
  {
    id: 3,
    data: 'some data',
    ...
    chosen: true,
    user:'Logan'
  },
  {
    id: 5,
    data: 'some data',
    ...
    chosen: true,
    user:'Felix'
  }
]

I want to update the chosen and user field in the initial state with the array of object's chosen and user, which I received in the Axios call. I was thinking of a logic where I can compare the received object's id with the state's object id. If they're equal I'll update the chosen and user (using the spread operator) if not I'll just return the state's object. I'm not sure how to map through the state or the received list of objects and compare the ids. Please, someone help me with this logic.

Upvotes: 1

Views: 60

Answers (1)

Istvan Szasz
Istvan Szasz

Reputation: 1567

return {
      ...state,
      someData: state.someData.map(item => {
        const replaceWith = updatedData.find(
          updatedItem => item.id === updatedItem.id
        );
        return replaceWith
          ? { ...item, chosen: replaceWith.chosen, user: replaceWith.user }
          : item;
      })
    };

Upvotes: 1

Related Questions