Fellow Stranger Fellow Stranger - 6 days ago 4
React JSX Question

Resume prevented form submission in React

I'm implementing Stripe with React.

Upon submit click, the form submission is prevented and an ajax request goes to Stripe - giving us a token in the response which should be attached in the subsequent request to our server.

I'm stumbling on how to implement/trigger this subsequent request to our server?

Below is an example of this flow taken from the react-stripe-elements repository:

class _CardForm extends React.Component {
props: {
fontSize: string,
stripe: StripeProps,
}
handleSubmit = (ev) => {
ev.preventDefault();
this.props.stripe.createToken().then((payload) => console.log(payload));
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Card details
<CardElement
onChange={handleChange}
onFocus={handleFocus}
onBlur={handleBlur}
onReady={handleReady}
{...createOptions(this.props.fontSize)}
/>
</label>
<button>Pay</button>
</form>
);
}
}
const CardForm = injectStripe(_CardForm);

Answer

You should trigger your call to the server once you get your token, i.e in the then clause of the promise that this.props.stripe.createToken returns.

handleSubmit = (ev) => {
  ev.preventDefault();
  this.props.stripe.createToken()
    .then((payload) => yourFetchImplementation('path/to/api/endpoint', payloadAsBody));
}