setState delay in updating the state

559 Views Asked by At

I was sending all the data of my form to an api, but I can't do it, this is my code

const handleSubmit = () => {

       setData({
                ...data,
                apellidoParterno: inputs.apellidoParterno,
                apellidoMaterno: inputs.apellidoMaterno,
                nombres: inputs.nombres,
                cargocontacto: inputs.cargocontacto,
                telèfonocontacto: inputs.telèfonocontacto,
                celularcontacto: inputs.celularcontacto,
                emailcontacto: inputs.emailcontacto,
            })
            onSubmitProveedor();
       
    }

the information is stored correctly in setData, but the problem is that it takes a little time to do that and that is why what I send to the api is nothing. This function "onSuibmitProveedor" is my function where I am sending the data

1

There are 1 best solutions below

4
AKX On

Yes, setState is asynchronous; you can't read the updated data immediately.

You can either call onSubmitProveedor from an effect, e.g.

React.useEffect(() => {
  if(dataIsCompleteEnoughForSubmission(data)) onSubmitProveedor();
}, [data]);

or make onSubmitProveedor accept the data object and call it directly there:

const onSubmitProveedor = (data) => { ... };
const handleSubmit = () => {
  const fullData = {...data, apellido...};
  setData(fullData);
  onSubmitProveedor(fullData);
}