Reputation: 806
I've created a react app where a logged-in user can upgrade their account using Stripe.
I'm using the following tutorial to implement Stripe/Express: https://hackernoon.com/stripe-api-reactjs-and-express-bc446bf08301
axios
.post("http://localhost:9000/payment", body)
.then(response => {
console.log(response);
alert("Payment Success");
})
.catch(error => {
console.log("Payment Error: ", error);
alert("Payment Error");
});
};
Testing the Stripe purchase in the React app works because I get POST /payment 200 737.717 ms - 2261
with my Express back end & can see the test payment data in the Stripe dashboard.
Now I want to push to a new view after the purchase is successful, so I tried using the .push
method after purchase:
axios
.post("http://localhost:9000/payment", body)
.then(response => {
console.log(response);
// alert("Payment Success");
props.history.push('/prowelcome')
})
.catch(error => {
console.log("Payment Error: ", error);
alert("Payment Error");
});
};
However, adding that line now results in displaying alert("Payment Error");
, however the payment is posting successfully to the backend.
I've also tried this.props.history.push
(which works other places in my app), but those working instances are in my main App.JS file where I have set state & routes for the app.
I thought of bringing this .js function into App.js, however, the code in the tutorial where this axios/stripe post is included is not a class or functional component (I am a relative n00b to react), so I am sure how I would refactor this to work in app JS or how to fix the .push
method.
import React, { Fragment } from "react";
import StripeCheckout from "react-stripe-checkout";
import axios from "axios";
const stripeBtn = (props) => {
const publishableKey = process.env.STRIPE_PK;
const onToken = token => {
const body = {
amount: 9600,
token: token
}; axios
.post("http://localhost:9000/payment", body)
.then(response => {
console.log(response);
// alert("Payment Success");
this.props.history.push('/prowelcome')
})
.catch(error => {
console.log("Payment Error: ", error);
alert("Payment Error");
});
};
return (
<StripeCheckout
label="Go Premium" //Component button text
name="Business LLC" //Modal Header
description="Upgrade to a premium account today."
panelLabel="Go Premium" //Submit button in modal
amount={9600}
token={onToken}
stripeKey={publishableKey}
billingAddress={false}
/>
);
}
export default stripeBtn;
Upvotes: 0
Views: 1081
Reputation: 8794
You have to add the router to the component to have it passed in the props:
import { withRouter } from 'react-router';
export default withRouter(stripeBtn);
This will add the history, location and match props to this component.
After that, you can call this.props.history.push('/prowelcome')
.
Upvotes: 1