0

I have a modal that contains a form. Whenever I submit data through it and console log it, it never works the first time. The second time I submit data through it, the console log of the previous entry. Can anyone identify if I am potentially missing anything?

  const handleSubmit = (event) => {
    event.preventDefault();
    setOpen(false);
    setSubmission({
      ref: event.target[0].value,
      brand: event.target[1].value,
      iname: event.target[2].value,
      gtin: event.target[3].value,
      qty: 0,
    });
    console.log(submission);
  };
1
  • 1
    It is because the state is updating asynchronously. You won't get the updated values immediately Commented Nov 20, 2020 at 18:47

1 Answer 1

3

Well this is how hooks work, by the time you console.log(submission), the state hasn't changed yet.

This is because when you call setSubmission() it lets react know you want to update the state and puts it in a queue.

If you want to capture the state change, use an useEffect() hook

    useEffect(() => {
        console.log(submission); // this hook captures the state change and this will have the correct value
}, [submission]);  // think of this as a dependency variable that `useEffect` will listen for changes.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your great answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.