0

I have simple form where onChange value is updated as typed.

Example when type 12, only 1 is saved in the state and when type second time 123 only 12 is stored.

useState :

const [costsFormValues, setCostsFormValues] = useState({});

Function

const handleCostInputValues = (event, index) => {
    setCostsFormValues({
        ...costsFormValues,
        [event.target.name]: [event.target.value],
    });
    console.log(costsFormValues) //prints only 1 instead of 12
}

Form

<Form.Control type="number" onChange={e => handleCostInputValues(e, i)} />
the Hutt
  • 16,980
  • 2
  • 14
  • 44
  • how do i fix it ? – Deepak Murthy Apr 04 '21 at 08:37
  • it shows the values typed, which is 12 - only in the state it is saved as 1 – Deepak Murthy Apr 04 '21 at 08:39
  • @AheetShah It's more about closures. You literally cannot access the new value from the current closure. – Janez Kuhar Apr 04 '21 at 08:44
  • @JanezKuhar I think this question is about async nature of State Setter functions; Not related to closures. – Ajeet Shah Apr 04 '21 at 08:58
  • @DeepakMurthy You may also want to see [this](https://github.com/facebook/react/issues/11527#issuecomment-360199710), [this](https://reactjs.org/docs/react-component.html#setstate), [this](https://stackoverflow.com/q/41446560/2873538), [this](https://stackoverflow.com/q/54069253/2873538), [this](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous). – Ajeet Shah Apr 04 '21 at 09:01

0 Answers0