Home > Back-end >  Why component doesn't rerender?
Why component doesn't rerender?

Time:05-14

const [dammy, setDammy] = useState({
  name: "any",
  status: {
    "1.0.1": "Successfylly installed",
    "1.0.2": "Successfylly installed",
    "1.0.3": "Successfylly installed",
    "1.0.4": "Successfylly installed",
    "1.0.6": "Installing",
    "1.0.7": "In Queue",
    "1.0.8": "In Queue",
    "1.1.1": null,
    "1.1.2": null,
    "1.1.36": null,
    "1.1.4": null,
    "1.1.5": null,
    "1.1.6": null,
  },
  available: ["1.1.1", "1.1.2", "1.1.36", "1.1.4", "1.1.5", "1.1.6"],
  queue: ["1.0.7", "1.0.8"],
  date: new Date()
})

function addingToQueue(e: MouseEvent < HTMLDivElement > , i: number) {
  setDammy(prev => {
    let val = prev["available"].splice(i, 1)
    prev["queue"].push(val[0])
    console.log(prev) // <-- I could see changes has been applied
    return prev
  })
}

component doesn't rerender even tho I could see that in setDummy console show's the right object data. But after completing function pre-render doesn't happen and on a screen I see no changes.

CodePudding user response:

Because you're not actually returning a new array in your callback to setDammy-- you're merely mutating the previous one and returning it; when React does its comparison, it will see that the returned object is still the same reference. Instead, spread into a new array and alter that:

setDammy(prev => {
  const newArr = [...prev];
  let val = newArr["available"].splice(i, 1)
  newArr["queue"].push(val[0])
  console.log(newArr) // <-- I could see changes has been applied
  return newArr
})
  • Related