我在一个项目中,我必须在向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();
}
}
}
谢谢你的帮助
请尝试在调用函数前使用 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被改变,hook将监控变化并相应地执行希望这能帮助你理解。