Muteshi
Muteshi

Reputation: 1328

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

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([]);
}}

Upvotes: 2

Views: 1184

Answers (2)

mercury
mercury

Reputation: 2765

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)
    );
  };

Upvotes: 0

WebbH
WebbH

Reputation: 2422

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]);

Upvotes: 2

Related Questions