thatguy
thatguy

Reputation: 410

How Do I Redirect My Frontend React Application From External API Call

I am building a mini project and I am using a Payment Processor called Paystack. Typically, when a payment is initiated by the user, the payment processor generates a unique link for that current payment transaction. All the payment processor requests are set up in the Backend, I am using NodeJS and Express basically. Now my current issue is redirecting the frontend to the payment gateway using the generated link. The code for handling that looks like this basically.

    const config = {
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization:
          "Bearer ApiKey",
      },
    };
    try {
      const res = await axios.post(
        `${API_URL}/payment/paystack/pay/${ref}`,
        config
      );
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };

The result of res is the link generated. How do I make my frontend goto the generated link?

Any help would be appreciated. Thank you.

Upvotes: 0

Views: 1318

Answers (3)

Mustakim
Mustakim

Reputation: 429

You could simply call window.open() and pass the link as an argument. For example

 window.open("https://www.w3schools.com");

Or you could use react-router

Upvotes: 1

polyglot
polyglot

Reputation: 862

If it's the React app link, use React history.

For React class component:

this.props.history.push(url);

For React hook:

import { useHistory } from "react-router-dom";
...
const history = useHistory();
...
history.push(url);

If it's an external link, you should not use React stuff. Just use window.location:

window.location.href = url;

Upvotes: 1

Prateek Thapa
Prateek Thapa

Reputation: 4938

You could assign your link to window.location and let your browser handle the rest.

window.location = link;

Upvotes: 1

Related Questions