我想使用API验证表单数据。根据API调用的结果,我是否要提交表单。如何确保在useState成功之前第二个API调用不会完成?
我查看了关于Hooks的React文档,但是没有看到useState上的回调。
const getValidaterNumber = async () => {
try {
const response = await axios.post(`${process.env.REACT_APP_API_URL}validatenumber`,
{
sector: input.sector,
nr: input.Number
});
return await response.data;
} catch (error) {
console.log(error);
}
};
const handleSubmit = async (event) => {
event.persist();
event.preventDefault();
event.stopPropagation();
const form = event.currentTarget;
setValidated(true);
if (form.checkValidity()) {
if (!isNumberValidated) {
let data = await getValidateNumber();
if (!data.error) {
setInput((input) => ({...input, 'Number': data.nr}));
setInput((input) => ({...input, 'sector': data.sector}));
} else {
return;
}
setIsNumberValidated(true);
}
const response = await props.handleSubmit(event, {
Number: input.Number,
comment: input.comment,
sector: input.sector
});
if (response.error) {
console.log(`${response.error.errormessage}`)
} else {
setInput(initialState);
setIsNumberValidated(false);
setValidated(false);
}
}
};
提交“ props.handleSubmit”时,来自API调用getValidateNumber的数据应位于对象“ input”中。目前,我看到数据是从getValidateNumber返回的,但是旧数据正在发送到'props.handleSubmit'。