Home > database >  React useState setter is not working on a boolean value
React useState setter is not working on a boolean value

Time:01-20

I tried updating a state value using its setter from the useState hook, but it wouldn't update. The same setter is working in a different function while setting the value true.

To make sure that the function call was proper, I tried updating a different state from the the faultering function and it works!

I have been whacking my head as to why that particular state is not updating to a boolean false value.

const initialFormState = {
  0: { a: null, b: 0.0, c: 0.0 }
};
const [form, setForm] = useState(initialFormState);
const [fileUploadModal, setFileUploadModal] = useState(false);

function openFileInput() {
  setFileUploadModal(true);  // this works fine
}

function closeFileInput() {
  setFileUploadModal(false);   // this doesn't update
  setForm(initialFormState);   // this works fine as well
  console.log(fileUploadModal, form);
}

To sanity check:

useEffect(() => {
  console.log('File open state modified', fileUploadModal);
}, [fileUploadModal]);

This is not updated proving that there is some issue with the state setter.

CodePudding user response:

Sounds like setstate-doesnt-update-the-state-immediately. Setter is working correct , you must know that setFileUploadModal is asyncronous, you can check updated state in useEffect. Example:

const initialFormState = {
    0: { a: null, b: 0.0, c: 0.0 }
  };
  const [form, setForm] = useState(initialFormState);
  const [fileUploadModal, setFileUploadModal] = useState(false);

 function openFileInput() {
    setFileUploadModal(true); 
  }

  function closeFileInput() {
    setFileUploadModal(false);
    setForm(initialFormState);
  }

useEffect(() => {
   console.log(fileUploadModal);
}, [fileUploadModal])

CodePudding user response:

So sorry for the question, but the problem was due to a template issue, the click also triggered the function which sets the value to true. The confusion arose because the state update useEffect was not called, and that lead me to different line of investigation. The real issue was the btn click was not propagated properly.

Thanks for the help everyone!

  •  Tags:  
  • Related