Reputation: 73
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);
};
Upvotes: 0
Views: 47
Reputation: 61
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.
Upvotes: 3