Home > Net >  How to simultaneously update multiple object's values inside an array
How to simultaneously update multiple object's values inside an array

Time:02-25

I'm trying to simultaneously update 2 object's values inside an array when an onClick function is called. Currently I am able to decrement the target (selected) value by 1 (e.g -1) but am in need of suggestions for my next expectation:

If a previous value exists (e.g an option is selected) and I select a different option (radio button) I expect the previous value to increment by 1 ( 1) simultaneously to the new value being decremented.

Array Structure:

`(4) [{…}, {…}, {…}, {…}]
0: {name: 'Space pod', total_no: 2, max_distance: 200, speed: 2}
1: {name: 'Space rocket', total_no: 1, max_distance: 300, speed: 4}
2: {name: 'Space shuttle', total_no: 1, max_distance: 400, speed: 5}
3: {name: 'Space ship', total_no: 2, max_distance: 600, speed: 10}`

Current:

const handleVehiceChange = (e) => {
setValue(e.target.value);
setVehiclesData(
  vehiclesData.map((vehicle) =>
    vehicle.name === e.target.value
      ? { ...vehicle, total_no: vehicle.total_no - 1 }
      : vehicle
  )
)};

CodePudding user response:

Rather than overwriting the previous state with new state with a decremented total_no, I'd have a function that calculates the decremented result without putting the result into state. This makes it easy to switch between selected names to decrement.

const handleVehiceChange = (e) => {
  setValue(e.target.value);
};
const makeMergedData = () => vehiclesData.map((vehicle) =>
  vehicle.name === value // from state
    ? { ...vehicle, total_no: vehicle.total_no - 1 }
    : vehicle
);

Then replace consumers of vehiclesData with makeMergedData().

If the vehiclesData isn't being changed anywhere else, this might let you remove it from state completely.

  • Related