[英]React onSubmit wait for async IIFE inside the function to update state with hooks
有没有办法等待这个状态(customerId => setCustomerId)更新?
当用户注册时,他/她将被重定向并卸载表单。
我尝试使用 IIFE,所以它在提交后立即运行,但运气不好,useEffect 也不会工作,因为我无法将 onSubmit function 包装在 useEffect scope 中,至少我认为它不会工作。
有人可以启发我吗,在注册时更新 firebase 中的用户文档(这是 UserDataProvider() 所做的)以防止将来出现并发症是至关重要的。
const onSubmit = (formData: FormData) => {
document.body.style.cursor = 'wait';
(async function () {
const customer = await axios.post('/api/create_customer', {
email: 'testemail@test.com',
name: `Dario Kolic`,
});
setCustomerId(customer.data);
})();
console.log(customerId);
return auth
.createUserWithEmailAndPassword(formData.email, formData.password)
.then(() => {
return new UserDataProvider().set({
customerId: customerId,
});
})
.then(() => {
document.body.style.cursor = 'default';
// window.location.href = '/terms_of_service';
});
};
问题
第一个 IIFE 只有异步调用,这就是为什么第二个返回立即执行而不等待 customerid 更新。 这意味着在 customerid 更新之前执行的第二个 function
最好使用默认值then callback
function 而不是等待。 为什么要在onsubmit
事件中使用 return 语句。 我认为那应该没有影响。
const onSubmit = (formData: FormData) => { document.body.style.cursor = 'wait'; axios.post('/api/create_customer', { email: 'testemail@test.com', name: `Dario Kolic`, }).then((customer) => { setCustomerId(customer.data); auth.createUserWithEmailAndPassword(formData.email, formData.password).then(() => { return new UserDataProvider().set({ customerId: customer.data, }); }).then(() => { document.body.style.cursor = 'default'; // window.location.href = '/terms_of_service'; }); }) };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.