How To Wait To Export React Component Until After A Request. (Shopify App Development)

Viewed 163

First off, I'm completely new to Shopify App Development, as well as React and Next.js, so this may be a slightly stupid question. I'm currently sending a request to a website, and I'm using the response in the React component that I'm exporting/rendering, so I need to wait until I have that response to export my React component, so it's not undefined. Here's the code:

 if (typeof window === 'undefined')
  { 
    axios(config) // the actual request I'm waiting on
    .then(function (response) {
      siteHTML = response.data; // the element I'm adding to the react //component
    })
    .catch(function (error) {
      console.log(error);
    });
  }


// I need to define this function after I have the variable "siteHTML"
// If I define it with 'let' outside of the function first and then reassign 
// it after the response, react uses the first empty assignment. If I define 
// it in the function, it's a local not global variable.
  const Index = () => ( // The Actual Next.js/React Export To Be Rendered
<div>
  <h1>Site HTML:</h1>
  <div>
    { siteHTML }
  </div>
</div>
)



export default Index; 

Basically, the Index function needs to be defined after the response from the Axios request. I can't define Index and run 'export default index' inside the '.then', because 'export default index' needs to be on the top layer. I can't define Index inside the '.then' because then it's local to the function. And I can't define Index outside the function then set the value inside the '.then', because react will use the initial empty assignment.

That's my problem! I'm sure there's some obvious solution that someone will see in two seconds, but I just can't. Thank you for any help!

1 Answers

I think the key element you're missing is using a conditional render. You can actually apply this to the whole return statement...

Something like:

const Index = () => { 
  return !siteHTML ? (
    <div>loading...</div>
   ) : (
      <div>
        <h1>Site HTML:</h1>
        <div>
          { siteHTML }
        </div>
      </div>
   )
}

So if siteHTML does not exist yet - return a loading spinner or loading text or whatever you want. Once the request completes and siteHTML, the return function will swap over and render that instead.

Related