Using URL gotten from API response

24 Views Asked by At

I am using react-paystack to make a payment in an app but the backend of the code I am writing was configured such that when I call the order endpoint (a post request), I get a paystackResponse in the response of the successful call and among the response in the paystackResponse includes a URL that should be used to redirect the user to the paystack screen where the payment will be made. I tried to get the response straight from the API call by saving the res.data.data to a variable. I then used window.location.href = the URL gotten from the response which I already saved with a variable. So I wrote this window.location.href code after the line where the order endpoint has been called but because of this, the order endpoint that was returning successful before is coming as an error and the href to be redirected to is returning as undefined. It seems like I am not explaining my problem well so I will add the code and images for better context;

createOrder(payload: object) {
const request = createAxiosInstance(this.token);
runInAction(() => (this.loading.getOrders = true));
request
  .post(
    `${BaseDirectories.API_BASE_URL}/api/v1/food-order/create-order`,
    payload
  )
  .then((res) => {
    toast.success("Order created");
    // console.log('create order data', res.data.data)
    this.setCreateOrderRes(res.data.data)
    runInAction(() => (this.loading.getOrders = false));
  })
  .catch((error) => {
    runInAction(() => (this.loading.getOrders = false));
    return ErrorHandler(error);
  });

} so I am using mobx and the above code is the endpoint to create an order and it is the endpoint that is returning the paystackResponse on successful call. It can be seen in the code how I am handling the response and setting the res.data.data to "setCreateOrderRes" which is an empty object.

const { paystackResponse } = createOrderRes

I destructured paystackResponse in the above code and setting it to the window.location.href below,

window.location.href = paystackResponse?.authorizationUrl

and it should be noted that I am writing this code inside the same function that is calling the createorder endpoint but it comes after the code is successful. But this code I am writing with the window.location.href is now making the API call to fail and the URL is showing as undefined. I hope I have been able to make my problem a little easier to understand.

0

There are 0 best solutions below