'How to get first input value in react onChange and use it in onChange?
I can't make react onChange to fire on the first keystroke, the second input works. My goal is to get the new fName value to be used in other functions.
export default function Name() {
const [fName, setfName] = React.useState("");
return (
<input
type="text"
placeholder="First Name"
onChange={(e) => {
setfName(e.target.value);
console.log("fname", fName);
someOtherFunctions(fName); // i need to keep the function here to react to each user input change. how to get the right fName value here?
}}
/>
}
Typing 'abcd' and console prints:
fname
fname a
fname ab
fname abc
Solution 1:[1]
try this approach do console.log before of return whenever state will change it will re-render the page. Have a look at this code
import "./styles.css";
import React , {useState , useEffect} from 'react'
export default function App() {
const [fName, setfName] = useState("");
// every time state change react will automatically re-render the page
// console.log(fName)
function PrintMyState(state){
console.log(state)
}
// calls whenever state will be change , another approach
useEffect( ()=>{ PrintMyState(fName) } , [fName] )
return (
<input
type="text"
placeholder="First Name"
onChange={(e) => {
setfName(e.target.value)
}}
/>
);
}
sand Box Demo click here
Solution 2:[2]
Reactjs state is asynchronously updated, and batching within the function. So logging within the function itself the last state "" will be printed.
--> Try moving console.log("fname", fName); right before your return function.
Solution 3:[3]
onChange function is fired in every keystroke. It looks like you misunderstand something about React Hooks. In your code, setfName is working asynchronously, so first console log prints the previous fName. console.log("fname", fName + e.target.value); will print current value correctly. or You can use useEffect hook to print current value.
Solution 4:[4]
you need to put value={fName} for the input to work:
<input
type="text"
value={fName}
placeholder="First Name"
onChange={(e) => {
setfName(e.target.value);
console.log("fname", e.target.value);
}}
/>
for logging, run a useEffect call that runs everytime fName changes:
useEffect(() => {
console.log(fName)
}, [fName])
the dependency array [fName] means that run the function inside useEffect, in this case console.log(fName) every time fName changes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ryan Le |
| Solution 3 | Bo King |
| Solution 4 |
