Home > Software design >  React state is not updating immediately after setState is being called
React state is not updating immediately after setState is being called

Time:03-08

I am building the frontend of a web based software and I want to add new note every time I press add button.

But it's simply not happening. New note is being rendered only when I change the state of another object. Right below I ma attaching the code. Please help, I am stuck here.

const [allnotes, setAllNotes] = useState(notes)

const addNote = () => {
  let notesAllTemp = allnotes;
  allnotes.forEach((n, index) => {
  if((n.id === clickedId)){
     notesAllTemp[index].notesDescs.push({id: 
      notesAllTemp[index].notesDescs.length 1,desc:''})
      setAllNotes(notesAllTemp)
    }
  });
}

If anyone can figure this out, please help.

CodePudding user response:

Please don't make mistake by directly updating the array element by its index you should first copy the array into a new array, otherwise, it will directly update the array which will cause reacjs to not to re-render the component.

Check this out

const [allnotes, setAllNotes] = useState(notes)

const addNote = () => {
  let notesAllTemp = [...allnotes]; // !IMPORTANT to copy array
  allnotes.forEach((n, index) => {
  if((n.id === clickedId)){
     notesAllTemp[index].notesDescs.push({id: 
      notesAllTemp[index].notesDescs.length 1,desc:''})
      setAllNotes(notesAllTemp)
    }
  });
}

CodePudding user response:

Better if you first modify the array then update at once

const [allnotes, setAllNotes] = useState(notes)

const addNote = () => {
  let notesAllTemp = allnotes;
  allnotes.forEach((n, index) => {
    if((n.id === clickedId)){
      notesAllTemp[index].notesDescs.push({id: 
      notesAllTemp[index].notesDescs.length 1,desc:''})
    }
  });
  setAllNotes(notesAllTemp)
}
  • Related