1

I've been plopped into the middle of a react project with no prior knowledge so I'm sure this a duplicate.

I want to use the StripeElements, and the react library is easy enough. I'm just not sure how to get the client secret from the server.

This is what I'm trying:

const stripePromise = loadStripe('stripe_key');

const StripeForm = () => {

    const [stripeData, setStripeData] = useState({});

    const getClientSecret = async () => {
        const { data } = await api.get(`payment/stripe/get-client-secret/`);
        return data
    }

    useEffect(() => {
        getClientSecret().then(data => setStripeData(data))
    }, [])

    if(stripeData.clientSecret) {
        return (
            <QuoteContainer title={"Pay With Credit Card"}>
                <SectionCard>
                    {stripeData.clientSecret}
                </SectionCard>
            </QuoteContainer>
        );
    }

    return (<b>Loading</b>)
}

The route payment/stripe/get-client-secret/ returns an array with a key 'clientSecret'. This function is working correctly.

I just can't get the <b>Loading</b> text to be replaced with the QuoteContainer component once the promise is resolved.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Josh
  • 186
  • 1
  • 3
  • 17
  • can you log what's coming from getClientSecret()? – Alexander B. Mar 07 '22 at 05:16
  • also add ```.catch(handleError)``` just to make sure everything works as intended (you can log error there if you want). – Alexander B. Mar 07 '22 at 05:24
  • also have a look at this answer (https://stackoverflow.com/a/53572588/3500157) how you can write useEffect with async stuff in it (better to choose either then's or async/await style). – Alexander B. Mar 07 '22 at 05:29
  • 1
    Was a wrong key name, thanks guys. Was getting client_secret not clientSecret. – Josh Mar 07 '22 at 05:32
  • can you share what your doing on your server side? The `payment/stripe/get-client-secret/` endpoint? – conor909 Aug 28 '22 at 19:04

2 Answers2

1

If you want to rendering Loading component. You have to set falsy value for stripedData state. Because {} value is truthy. So I think the code is not rendering Loading component. The loading component is not rendered because there is no place to set it as a false value anywhere.

Codiving
  • 168
  • 8
0

what AJAX library are you using to make the API call? Usually you need to call a function on the response object in order to access the data. For instance, if you are using fetch(), you need to call json() then access the response data.

qichuan
  • 1,110
  • 7
  • 8