我接下来要做的是:付款成功后更新令牌(上下文)并将它们显示在用户面板组件中。目前,我正在将用户输入 (purchasedCoins) 解析为一个整数,并将 purchasedCoins 设置为等于数量。如果数量小于 0,我想抛出错误,否则,我想将数量保存到 localStorage 并使用 setTokens(quantity) 更新令牌。我已经为此苦苦挣扎了两天,非常感谢任何帮助。 按照 stripe docs 建立了后端,但没有成功,有些可疑的事情发生了。在代码中,我提供它只需要前端,因为它会在点击时重定向到条纹
问题:代码不更新令牌
const { tokens, setTokens } = useContext(TokensContext);
const [purchasedCoins, setPurchasedCoins] = useState(0);
const handleTokenChange = (e) => {
setPurchasedCoins(e.target.value);
};
const handleBuyClick = async () => {
const stripe = await stripePromise;
const quantity = parseInt(purchasedCoins);
console.log("quantity:", quantity);
if (quantity > 0) {
const { error } = await stripe.redirectToCheckout({
lineItems: [{ price: "price_Moded For Stack", quantity }],
mode: "payment",
successUrl: `${window.location.origin}/UserPanel`,
cancelUrl: `${window.location.origin}/UserPanel`,
});
console.log("error:", error);
if (!error) {
console.log("updating tokens:", quantity);
setTokens(quantity);
}
console.log(
"localStorage.tokenQuantity:",
window.localStorage.getItem("tokenQuantity")
);
window.localStorage.setItem("tokenQuantity", quantity);
} else {
console.error("Invalid quantity value");
}
};
-----------------------------------------------------
//Updated code only updates tokens until page refereshed
const handleBuyClick = async () => {
const stripe = await stripePromise;
const quantity = parseInt(purchasedCoins) || 0;
if (quantity > 0) {
const { error } = await stripe.redirectToCheckout({
lineItems: [{ price: "price_Moded For Stack", quantity }],
mode: "payment",
successUrl: `${window.location.origin}/UserPanel`,
cancelUrl: `${window.location.origin}/UserPanel`,
});
if (!error) {
console.log("success: Updating token quantity");
const currentQuantity = parseInt(localStorage.getItem("tokenQuantity")) || 0;
const newQuantity = currentQuantity + quantity;
localStorage.setItem("tokenQuantity", newQuantity);
setTokens(newQuantity);
setQuantity(0);
setPurchasedCoins(""); // clear input
}
} else {
console.error("Invalid quantity value");
}
};