0

Given the following code:

 const handleSubmit = (event) => {
    event.preventDefault();
    console.log("telFormValues when submit:"+JSON.stringify(telFormValues));
    setFormValues({
      ...formValues,
      "telefonos_empresa": telFormValues,
      "emails_empresa": emailFormValues
    });

Which is part of a form using TextFields with onChange, when text is placed in a input and I click the submit button directly,(handleSubmit is called) the console.log for telFormValues shows the data from the form correctly, however, formValues does not register the last input, unless I click out of it. It happens with any input in the form if it is the last one, if the user clicks submit directly, is not 'saved'. I don't understand why is this behaviour happening and after all, the console shows that the value is indeed there, but for some reason it is not setting on setFormValues.

console.log(JSON.stringify(formValues["telefonos_empresa"])) shows: [{"tel_identificator":"test1","tel":"234"}]

console.log(formValues) (placed right in the following line) shows: telefonos_empresa: []

Edit: Per suggestion, tried:

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log("telFormValues en submit:"+JSON.stringify(telFormValues));
    setFormValues({
      ...formValues,
      "telefonos_empresa": telFormValues,
      "emails_empresa": emailFormValues
    }, 
        console.log(JSON.stringify(formValues["telefonos_empresa"])),
        console.log(formValues)
      );
  };

But the result is the same.

Germán
  • 1,007
  • 1
  • 7
  • 20
  • @NickVu could you check it please? – Germán May 05 '22 at 12:28
  • https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately this should help – El Pandario May 05 '22 at 12:31
  • @ElPandario if I'm not wrong, they say in this link that setState() in React is asynchronous, so I put the console.log inside a setTimeOut to 3 seconds and still the same result. – Germán May 05 '22 at 12:48
  • Have you tried to make the function async and use await? – El Pandario May 05 '22 at 13:00
  • I mean, I don't think I have something abnormal in my code. Does every form in react need to manipulate a simple submit function? I don't think this is the premise to solve it. – Germán May 05 '22 at 13:07
  • What I usually do to counter this problem, is that I make an handleChange (which basically update the state) function on my inputs. That way when I submit my form all states are updated. – El Pandario May 05 '22 at 13:16

0 Answers0