Replace an existing object in state with another object using react hooks usestate

Viewed 423

I have the following code which is supposed to check if an object exists in state and replace it and if not append it to the state. So far appending to the state works correctly but when replacing the object the UI is not updated accordingly.

const [roomData, setRoomData] = useState([]);
 .............
onSelectRoom={(room) => {
  let roomIndex = roomData.findIndex(
    (room) => room.roomId == item.id
  );
  roomData[roomIndex]
    ? (roomData[roomIndex] = room)
    : setRoomData([...roomData, room]);
  setRoomTotals([]);
}}
2 Answers

Its not updating properly because you are directly mutating the state. You need to either make a copy of the state and change that and update the state like:

const newState = [...roomData];
newState[roomIndex] = room;
setRoomData(newState);

or you can try something like:

roomData[roomIndex] ? setRoomData(roomData.map((data,i)=>{
  if(i === roomIndex){
    return room
  }
  return data;
}) : setRoomData([...roomData, room]);

Note : You are not allowed to mutate the state directly .

This should do the trick, By Functional Programming.

  const onSelectRoom = (room) => {
    setRoomData((prev) =>
      prev.find((r) => r.id === room.id)
        ? prev.map((r) => (r.id === room.id ? room : r))
        : prev.concat(room)
    );
  };
Related