React state lagging behind reality, causing MUI to display wrong dialog

Viewed 15

On a button, I have a onClick handler

  const handleSelectOpen = (noteId) => {
    let newState = {notes: state.notes, noteDetailScreen: true, activeNote: noteId, newNoteScreen: false, newNoteText: "", newNoteRelated: []};
    setState(newState);
  };

Which does two important things, it sets noteDetailScreen in the state to true, causing the MUI Dialog to appear. It also sets activeNote to noteId, which is the content that should be displayed in the dialog.

That content is then displayed with {state.notes[state.activeNote].content} inside the dialog. The issue being most of the time, its displaying the wrong content! noteId is always correct, but the state is not always correct. How can I fix this>

1 Answers

when updating state based on the previous state, you should pass an updater function to setState. It takes the pending state and calculates the next state from it.

setState(prev => ({notes: prev.notes, noteDetailScreen: true, activeNote: noteId, newNoteScreen: false, newNoteText: "", newNoteRelated: []}))

Related