Skip to content
Advertisement

setState only setting last input when using object as state

Im trying to create a form with React. This form uses a custom Input component I created various times. In the parent form Im trying to get a complete object with all names and all values of the form:

JavaScript

For this, I created a ‘component updated’ hook, that calls the function property onNewValue to send the new value to the parent (two way data binding):

JavaScript

The parent form receives the data in the handleInputChange function:

JavaScript

This way all elements from all inputs should be set on init:

JavaScript

But for some reason only the last one is being set:

JavaScript

You can find the bug here: https://codesandbox.io/s/react-typescript-vx5py

Thanks!

Advertisement

Answer

The set state process in React is an asynchronous process. Therefore even if the function is called, values has not updated the previous state just yet.

To fix, this you can use the functional version of setState which returns the previous state as it’s first argument.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement