0

I stored string that typed in input tag but it isn't same as typed.

const[name,setName]=useState('');
.....
.....
<input type="text" placeholder='search' onChange={(event)=>{setName(event.target.value)}} value={name}/>

please enter a sample string and then see the console

https://codesandbox.io/s/goofy-dust-gsg9co?file=/src/App.js

Ali Mahmoudi
  • 83
  • 2
  • 8
  • useState is asynchronous that's why it misses the last letter when you console.log(name) just after useState. If you console.log before the return statement you will see the right value – J.dev May 03 '22 at 18:25

2 Answers2

1

States updates are asynchronous, so when you set a new state value and console.log() right after it, it's going to show the previous value, because the state hasn't been updated yet.

That's why your name value show the old value of the state in the console on CodeSandbox.

1

In your code sandbox, you console.log(name) right after having set it to the value of the input. The problem here is that setName is an asynchronous function, meaning that when it is called your program won't wait for the response. Instead, it'll keep going and so in your instance, setName hasn't updated name when you log it. This is why you always see the previous string that was saved to name.

Nicolas A.
  • 31
  • 3