You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
CodeSandBox here
Image a button for buy a goods, userInfo has three state: unLogin, login, and vipLogin.
Only vipLogin can but this goods.
I want to bind a function to this button to handle different logic while different user state.
const Buy = () => {
const { data: userData, mutate } = useMutation({
mutationFn: () =>
Promise.resolve({
isLogin: true,
}),
mutationKey: ["login"],
});
const isLogin = userData?.isLogin;
const { data: vipInfo } = useQuery({
queryKey: ["vipInfo"],
enabled: Boolean(isLogin),
queryFn: () =>
new Promise((resolve) => {
setTimeout(() => {
resolve({
isVip: true,
});
}, 2000);
}),
});
const handleBuyAgain = () => {
// because of queryVipInfo is an async way , so we can not get right VipInfo. undefined here
console.log(vipInfo, "vipInfo of handleBuyAgain");
};
const handleBuy = () => {
console.log("handleBuy");
if (isLogin) {
if (vipInfo?.isVip) {
console.log("buy good successfully");
} else {
console.log("please buy vip first");
}
} else {
mutate(
{},
{
onSuccess: () => {
console.log("login success");
handleBuyAgain();
},
onError: (e) => {
console.log("login error", e);
},
},
);
}
};
return (
<>
<button onClick={handleBuy}>buy</button>
<br />
isLogin:{isLogin ? "true" : "false"}
<br />
isVip:{vipInfo?.isVip ? "true" : "false"}
</>
);
};
But vipInfo is an async way (maybe 10 seconds), handleBuyAgain can't get right vipInfo here .
I just find a way to handle this, but it's so bad.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
CodeSandBox here
Image a button for buy a goods, userInfo has three state: unLogin, login, and vipLogin.
Only vipLogin can but this goods.
I want to bind a function to this button to handle different logic while different user state.
But vipInfo is an async way (maybe 10 seconds), handleBuyAgain can't get right vipInfo here .
I just find a way to handle this, but it's so bad.
is there a better way to handle handleBuyAgain?
Beta Was this translation helpful? Give feedback.
All reactions