0

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
user3810193
  • 53
  • 1
  • 8

4 Answers4

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

zain ul din
  • 1
  • 1
  • 2
  • 23
0

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.

Ryan Le
  • 7,708
  • 1
  • 13
  • 23
-2

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.

Bo King
  • 62
  • 6
-2

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.

deadcoder0904
  • 7,232
  • 12
  • 66
  • 163