I am trying to determine if a customer has an active subscription or not. To do this I am utilizing the following code:
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 ) }
I have been able to successfully get all of my other functions where I am doing the comparisons for if a user is a subscriber but where I am having an issue is updating the state value (e.g. true if they are subbed, false otherwise).
I found some good past questions on this specific topic such as: here The useState set method is not reflecting a change immediately
here: setState inside Promise in React
and here: setState inside a Promise function in a useEffect with hooks?
but I just have not been able to get it working correctly. This is currently the closest I have been able to get to solving this problem.
Advertisement
Answer
Currently your code says that, when isSubscriber
changes, it should check if the user is a subscriber and update the isSubscriber
state… so it’s a chicken and egg problem. It won’t set isSubscriber
until isSubscriber
gets set.
I think you want to change }, [isSubscriber]);
to }, []);
so that that code executes when the component first loads (not when isSubscriber
changes).