Reputation: 47
I am working on a form with two input boxes. On form submission, I have to take these values and concat them to an array. Once done, I need to display them.
I used states for this however, I'm facing a weird issue: every time I update a state, I cannot get the updated state in the function.
const [a, updateA] = useState('1')
// ...
// Assume this is called when form is submitted
const updation = (event) => {
updateA(event.target.value)
console.log(a) // prints 1 instead of the new value
}
How do I fix this?
Upvotes: 0
Views: 56
Reputation: 1375
useState()
is asynchronous. React does not guarantee that the state changes are applied immediately. useState()
does not always immediately update the component. Think of useState()
as a request rather than an immediate command to update the component.
So you can not see the result immediately inside the method.you can use useEffect
:
useEffect(() => {
// action on update of a
}, [a]);
and
const [a, updateA] = useState('1')
const updation = (event) => {
updateA(event.target.value)
console.log(a) // prints 1
}
console.log(a) // prints updated Value
Upvotes: 1