publicArt33
publicArt33

Reputation: 315

updating multiple items in redux array

I am trying to update an array of objects in the redux state,

cars redux state

cars:  [
  {
    _id:"5b61b782719613486cdda7ec",
    car: "BMW",
    year: '2015'
   },
   {
      _id:"5b61b782719613486cdda7e1",
      car: "Toyota",
      year: '2015'
    },
    {
      _id:"5b61b782719613486cdda7e2",
      car: "Honda",
      year: '2015'
    },
    {
      _id:"5b61b782719613486cdda7e3",
      car: "Audi",
      year: '2015'
    }
 ]

action.payload array

 action.payload :      
   [
    {
      _id:"5b61b782719613486cdda7ec",
      car: "BMW",
      year: '2019'
    },
    {
      _id:"5b61b782719613486cdda7e3",
      car: "Audi",
      year: '2019'
    }
  ]


case UPDATE_CARS:
  const updatedCars = state.cars.map((car) => {
  action.payload.forEach((newCars, index) => {
    if (car._id !== newCars._id) {
      //This is not the item we care about, keep it as is
      return car;
    } else {
      //Otherwise, this is the one we want to return an updated value
      return { ...car, ...newCars };
    }
  });
});

return {
  ...state,
  cars: updatedCars,
  loading: false
};

As you can see I am trying to update multiple items in the redux array only if item exists in the redux state.

What am I doing wrong? Any suggestions?

Upvotes: 3

Views: 2651

Answers (2)

devserkan
devserkan

Reputation: 17638

Another alternative:

const updatedCars = state.cars.map( car => {
  const found = action.payload.find( el => el._id === car._id );
  return found ? found : car;
});

forEach does not return anything, it just executes the given function for the current element. So, for the situations like that map is your friend.

Even there is a shorter and nicer version which @Luke M Willis provided in the comments:

const updatedCars =
    state.cars.map(car => action.payload.find(el => el._id === car._id) || car);

Upvotes: 7

Arup Rakshit
Arup Rakshit

Reputation: 118299

I'll filter out the cars from state, which are present in action.payload. Then I'll merge the action.payload, and filtered state like below.

case UPDATE_CARS:
  const updatedCarIds = action.payload.map(o => o.id);
  const notUpdatedCars = state.cars.filters(car => !updatedCarIds.includes(car.id))
  return [...notUpdatedCars, ...action.payload]

Upvotes: 0

Related Questions