I'm trying to update object inside object in react hooks with useState

Viewed 32

I'm trying to update object inside object in react hooks with useState.

When I create it's ok, but when I try to update only the count it's deleting the neighbors.

This is the console after create

{fish1: {…}}
fish1:
count: 1
neighbors: Array(1)
0: Array(3)
0: "fish3"
1: "fish6"
2: "fish7"

after the update

{fish1: {…}}
fish1:
count: 2

This is the code that create or update

if (fishProfile.name in fishDictionary) {
  setFishDictionary({
    ...fishDictionary,
    [fishProfile.name]: {
      count: fishDictionary[fishProfile.name].count+1
    }
  })
} else {
  setFishDictionary({
    ...fishDictionary,
    [fishProfile.name]: {
      count: 1,
      neighbors: [fishProfile.Neighbors]
    }
  })
}
2 Answers
 if(fishProfile.name in fishDictionary){
            setFishDictionary({...fishDictionary,[fishProfile.name]:{count:fishDictionary[fishProfile.name].count+1,neighbors:fishDictionary[fishProfile.name].neighbors } })
         }
        else
        {
        setFishDictionary({...fishDictionary,[fishProfile.name]:{count:1,neighbors:[fishProfile.Neighbors]}})
        }

You are mutating state and removing properties when updating the fishDictionary state. When updating React state it is necessary to shallow copy all state, and nested state, that is being updated.

setFishDictionary(fishDictionary => {
  if (fishProfile.name in fishDictionary) {
    return {
      ...fishDictionary,
      [fishProfile.name]: {
        ...fishDictionary[fishProfile.name], // <-- shallow copy
        count: fishDictionary[fishProfile.name].count + 1
      }
    };
  } else {
    return {
      ...fishDictionary,
      [fishProfile.name]: {
        count: 1,
        neighbors: [fishProfile.Neighbors]
      },
    };
  }
});
Related