简体   繁体   中英

How to wait for onChange event to set Value using react hooks?

I want to access the value of value state variable inside handleKeyDown function. But, as I go on typing I notice that value is not set to the latest input value but the previous input state instead. I used setTimeout so that handleChange would be called first and setValue() function would change the value of value . And then changed value would be reflected inside handleKeyDown function.

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [value, setValue] = useState("");

  const handleChange = (e) => {
    console.log("called handle changed");
    setValue(e.target.value);
  };

  const handleKeyDown = (e) => {
    console.log("called keydown");
    console.log(value);
  };

  return (
    <div className="App">
      <input
        value={value}
        onChange={handleChange}
        onKeyDown={(e) => setTimeout(() => handleKeyDown(e), 0)}
      />
    </div>
  );
}

e.target.value shows the latest and required value, but value itself shows the old value. How to wait until handleChange sets the value using setValue and use value in handleKeyDown ?

You can use the useRef hook for the current value

`

import "./styles.css";
import { useState, useRef } from "react";

export default function App() {
  const [value, setValue] = useState("");
  const updatedValue = useRef("");

  const handleChange = (e) => {
    console.log("called handle changed");
    setValue(e.target.value);
    updatedValue.current = e.target.value;
  };

  const handleKeyDown = (e) => {
    console.log("called keydown");
    console.log(updatedValue.current);
  };

  return (
    <div className="App">
      <input
        value={value}
        onChange={handleChange}
        onKeyDown={(e) => setTimeout(() => handleKeyDown(e), 0)}
      />
    </div>
  );
}

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM