在请求API前先更新值

时间:2020-06-05 20:22:52

标签: reactjs react-hooks

我在一个项目中工作,在向API提出请求之前,必须多次修改该值。问题是,当我使用钩子更新值时,当我尝试更新值时,由于useState是异步的,因此值的更新保持在过去的值中。但是,在执行请求后,该值会被修改。

如何在我的请求前更新值?

代码如下:

useEffect(() => {                                  // I'm using a useEffect hook to verify that my variable is updated. But that update is done late.
    console.log(valorTotal);
}, [valorTotal]);

const agregarPlato = async () => {
    if(validarCamposPlato()){
        try{
            let valorParcial = 0;
            let platoExist = await encontrarPlato(config, rvPlato);
            if(platoExist === true){
                setAgregadoMin(true);
                platoCodigo = await obtenerCodigoPlato(config, rvPlato);
                platosRegVent.push({codigoPlato: platoCodigo, cantidad: rvCantidad});
                let costoPlato = await obtenerValorPlato(config, rvPlato);
                valorParcial = valorTotal;
                setValorTotal(valorParcial += (costoPlato * parseInt(rvCantidad)));      // Here is where I'm changing the value of my variable.
                setRvPlato('');
                setRvCantidad('');
            }
            else{
                toast.error('The object wasn't found.');
                setRvPlato('');
            }
        }
        catch(error){
            toast.error('An unexpected error has ocurred');
            props.handleSubmit();
        }
    }
}
const finalizarRegVent = async () => {
    console.log(agregadoMin);
    if(validarCampos()){  
        try{
            if(rvPlato !== '' || rvCantidad !== ''){
                agregarPlato();                                 // Here I'm calling the function above 
            }
            if(agregadoMin === true){
                rvCodigo = await crearRegistroVenta(config, valorTotal, fechaActual, regVentMesa);         // Here I'm doing the request to save the value
                platosRegVent.forEach( (plato : any) => {
                    crearRegVentPlato(config, rvCodigo, platosRegVent.codigoPlato, platosRegVent.cantidad);
                });
                valorFinal = true;

            }
            else{
                toast.error('You have to add an object before doing this option.');
            }  
        }
        catch(error){
            toast.error('An unexpected error had happened.');
            props.handleSubmit();
        }
    }
}

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

请尝试在调用函数之前使用await。

if(rvPlato !== '' || rvCantidad !== ''){
    await agregarPlato();
}

并在钩子事件内编写以下代码。

useEffect(() => {
    if(agregadoMin === true){
        rvCodigo = await crearRegistroVenta(config, valorTotal, fechaActual, regVentMesa);
        ...
    } else {
        toast.error('You have to add an object before doing this option.');
    }  
}, [agregadoMin])

然后,如果更改了agregadoMin,钩子将监视更改并相应地执行 希望这可以帮助您理解。