How to properly load global variable with async values(Reactjs)?

旧巷老猫 提交于 2020-04-17 22:10:28

问题


I'm trying to solve this problem that I can't seem to solve with stripe's API's

So when creating a charge with their new version API they say that in the front end we should call

loadStripe('publishable Key',{'Connected account ID'})

and set that to a const.

now I dont undestand how are we supposed to get the ID that is stored somewhere say a database?

As a reference please look at this and here (In Step 3 ...).

What I'm currently doing is something like this

import React from "react";
import ReactDOM from "react-dom";
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import CheckoutForm from "./CheckoutForm";

//btw I have set this to const and to let and none work
const stripePromise = fetch("url", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    anything: window.sessionStorage.getItem("Variable Account")
    //here store something that  will tell what account to pull ID data from
  })
})
  .then(data => data.json())
  .then(result => {
    return loadStripe("KEY", { stripeAccount: result });
  });

class App extends React.Component {
  render() {
    return (
      <Elements stripe={stripePromise}>
        <CheckoutForm />
      </Elements>
    );
  }
}

export default App;

but the const seems to not load correctly if one goes with the regular flow of the app say from

myapp.com/home  

-> click

myapp.com/home/something  

-> then

myapp.com/home/something/payment 

stripe is not loading but one refreshes the browser now works but that tells me I'm doing maybe something wrong or I have to make the app refresh in 'componentDidMount()' maybe?

One can set it to be static but connected accounts can be many so if anyone can help me with this I would appreciate it


回答1:


Generally, you'd want to have this account ID available in your app. But if you need to retrieve it, that's fine, but make sure the stripePromise is what you think it is. For example, I can make this work here with a simulated fetch call here: https://codesandbox.io/s/stripe-connect-w-resolve-wts34

Note that I'm managing the Promise explicitly:

const stripePromise = new Promise((resolve, reject) => {
  fetch(...)
  .then(data => data.json())
  .then(result => {
    resolve(
      loadStripe(STRIPE_PUBKEY, { stripeAccount: "acct_xxx" })
    );
  });
});

The fact that you describe this breaking with navigation suggests you might be routing incorrectly. If this is a single page app, the navigation shouldn't cause the App component to re-render.



来源:https://stackoverflow.com/questions/60589252/how-to-properly-load-global-variable-with-async-valuesreactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!