Home > database >  Can I rely on React state being updated in a form onSubmit handle?
Can I rely on React state being updated in a form onSubmit handle?

Time:08-16

React state updates are asynchronous, so you shouldn't do Edit elastic-gagarin-orjie1

Controlled Components

You mentioned that you "need to know if the rows it uses are always the ones actually displayed by the table". You can guarantee this by keep a single source of truth for the data by using controlled components.

Consider this example:

  const [email, setEmail] = useState("");
...
  return (
        <input
          value={email}
          onChange={(event) => setEmail(event.target.value)}
        />

Since we are setting the value of our input to the state variable email, we will always know that whatever value is displayed in the input field is the same as the value stored in the email state variable.

If we erroneously omit value like this: <input onChange={(event) => setEmail(event.target.value)} /> then we will have two sources of truth: 1. The DOM which handles the html input element, and 2. The state variable called email. This has potential to cause bugs later.

CodePudding user response:

I suggest using this code

const _handleChange = (event) => {
let temp =event.target.value;
  setEmail(temp);
  _updateEmailPermissions(temp);
};

I think using another event is working safely, but I think you can use a promise for that.

setAsyncState = (newState) =>
    new Promise((resolve) => this.setState(newState, resolve))

  • Related