Languages

Is the state updated when I submit a form in React?

3 points
Asked by:
Roaming_Hot_Dong
1060

I use a <form> in React and collect input data into a state using useState().

How to make sure that the data in the state is up-to-date when the 'submit' button is clicked?

1 answer
4 points
Answered by:
Root-ssh
178290

When you use, default events on <input> elements like onChangeonInput or onBlur to set state, the state is set imidiatelly by handling function. The problem occurs when event occurs in async mode that may be realised by some libraries. It that way, it is good to wait with submit action after all fieds will lose focus or then unlock submit button.

When async mode is used in events you can use some counter to check if all fields lost focus what was show in the second example.

Solutions

 

Simple React application using embedded <input> elements:

Source: https://dirask.com/snippets/Dl6lyj

 

Comples React application using cusomt async <Input> elements:

 

0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join