gpt4 book ai didi

javascript - 如何从 promise 中更新状态变量?

转载 作者:行者123 更新时间:2023-12-05 02:30:27 25 4
gpt4 key购买 nike

我正在尝试确定客户是否有有效订阅。为此,我使用了以下代码:

const stripe = require('stripe')('some-api-key');

export default function Example(){
// the user will automatically be considered non-subbed by default
const [isSubscriber, setIsSubscriber] = useState(false)


// grab the customer id from stripe
async function get_customer_id() {

const customers = await stripe.customers.search({
query: `metadata[\'some-meta-data-key\']:\'some-meta-data-value\'`
});
return customers.data[0]['id']
}


// grab the list of active subscriptions from stripe
async function customer_is_subscriber(){
const subs = await stripe.subscriptions.list({
status: 'active',
});
return subs
}


// determine if the customer id is in the list of active subscriptions.
// return true if so, false otherwise
async function test_equality(){
const customer_id = await get_customer_id();
const subbed = await customer_is_subscriber();

const answer = subbed.find(sub => sub.customer === customer_id)
return !!answer;

}


useEffect( () => {
async function load_result() {
const promise_function_return = await test_equality()
setIsSubscriber(promise_function_return)
}
load_result();
}, [isSubscriber]);


return (

// some react code

)

}


我已经能够成功地获得所有其他功能,我正在比较用户是否是订户,但我遇到问题是更新状态值(例如,如果他们被替代,则为 true,否则为 false ).

我发现了一些关于这个特定主题的过去的好问题,例如:这里The useState set method is not reflecting a change immediately

此处:setState inside Promise in React

这里:setState inside a Promise function in a useEffect with hooks?

但我就是没能让它正常工作。这是目前我能够解决此问题的最接近方法。

最佳答案

目前您的代码表示,当 isSubscriber 更改时,它应该检查用户是否是订阅者并更新 isSubscriber 状态...所以这是先有鸡还是先有蛋的问题问题。在设置 isSubscriber 之前,它不会设置 isSubscriber

我认为你想将 }, [isSubscriber]); 更改为 }, []); 以便该代码在组件首次加载时执行(而不是isSubscriber 更改)。

关于javascript - 如何从 promise 中更新状态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71850441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com