Home > Mobile >  How to update a form's input text state immediately in React using setState()
How to update a form's input text state immediately in React using setState()

Time:04-24

const [text, setText] = useState('');

const handleTextChange = (e) => {
   setText(e.target.value);
}

// Inside a form
<input onChange={handleTextChange} value={text} type="text" />

I'm trying to do something very simple but can't quite get it to work properly. From the code above, I have text and setText to store and update the state, and a function handleTextChange which gets called by the input field's onChange method.

I know that setState() is async so wont update immediately, however, If i need access to the updated result immediately how can I get it? I've read that useEffect hook can be used to do this but I can't figure out how I need to use it. If there is another way to accomplish this then please share.

The main objective is to get the "updated value of the text state variable" as the user is typing in the input field.

CodePudding user response:

yep you are right you need to use useEffect

you just need something like this

useEffect(()=>{
    // do something with updated value
 },[text])

this useEffect will have the updated value of text...basically it will run everytime setText is called and it sees an updated value for the text

Edit: or as comment suggested you can always use e.target.value for the latest value unless you really want to use state variable

you can use disabled={text.length===10}

credit to https://stackoverflow.com/users/633183/mulan

CodePudding user response:

I don't think useEffect is appropriate for what you are trying to do

function App({ onSubmit }) {
  const [text, setText] = React.useState("")
  return <form onSubmit={e => onSubmit(text)}>
    <input
      onChange={e => setText(e.target.value)}
      value={text}
      placeholder="enter a comment"
    />
    <button
      type="submit"
      disabled={text.length >= 10}
      children="disabled at 10 chars"
    />
    <p>{Math.max(0, 10 - text.length)} characters remaining...</p>
  </form>
}

ReactDOM.render(<App onSubmit={alert} />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

  • Related