This snippet implements a Stripe payments form on the client using React with XState and Effect.
The stripe logic is defined in a state machine using xstate
. The state machine tracks the current state of the form:
- Load
Stripe
(handle possible loading errors and allow reloading) - Wait for user to fill the form and submit
- Send a
confirmPayment
request to Stripe and report any errors
The stripe client is loaded inside a Stripe
service implemented using effect
. The service executes loadStripe
from @stripe/stripe-js
.
The React component uses useMachine
from @xstate/react
to load the state machine.
Loading stripe requires access to a
clientSecret
that should be provided by the server.
clientSecret
is required asinput
to the state machine.
The component renders Elements
from @stripe/react-stripe-js
. The code uses useElements
and useStripe
.
useElements
anduseStripe
can only be used inside a subcomponent wrapped insideElements
.
The form contains AddressElement
and PaymentElement
from @stripe/react-stripe-js
. When the form is submitted, the state machine is triggered with the stripe.submit
event.
When the payment is successful stripe will redirect to a success page defined when calling
confirmPayment
(return_url
).