title: Access Token in React.useEffect generally works, but comes back undefined when page is refreshed / reloaded
body: <p>I have a simple React page / component in Gatsby that makes an API call. For this API call I need a token. I use <a href="https://www.gatsbyjs.com/plugins/gatsby-theme-auth0/" rel="nofollow noreferrer">gatsby-theme-auth0</a> to obtain this token via their <code>AuthService</code> object.</p>
  <p>I am starting the API call in my <code>useEffect</code>. It looks like this:</p>
  <pre><code> useEffect(() =&gt; {
      //defining the async function
      async function fetchFromAPI() {
        try {
          const data = await fetchData()
          setData(data)
        }
      }
      
      //executing the async function:
      fetchFromAPI()
    }, [])
  </code></pre>
  <p>The function <code>fetchData()</code>, which is asynchronously called in <code>useEffect</code> currently looks like so:</p>
  <pre><code>async function fetchData() {
    
    const client = new GraphQLClient(SERVER_URL_GRAPHQL)
    let aToken = await AuthService.getAccessToken()
    client.setHeader('authorization', `Bearer ${aToken}`)
    const query = ...
  
    const data = await client.request(query)
    return data
  }
  </code></pre>
  <p>All of this <em>generally works</em>. When I navigate to this page, from a different page within my SPA it works. However, when I reload the page, it doesn't. the access token (<code>aToken</code>) then comes back as <code>undefined</code>.</p>
  <p><strong>But:</strong> <em>I can make things work</em>, when I wrap a <code>setTimeout</code> around the whole call. Then the access token comes back fine and isn't <code>undefined</code>. So I guess something first needs to initialise before <code>AuthService</code> can be called? I'm just not sure how to ensure this.</p>
  <p>But this is not what I want to do in production. Now I am wondering why this is. Maybe I am using <code>useEffect</code> the wrong way? Unfortunately, I have not been able to find anything online or on github so far. I'm sure the problem is rather basic though.</p>
  <p>EDIT: The <code>AuthService.getAccessToken()</code> method can be found <a href="https://github.com/epilande/gatsby-theme-auth0/blob/master/gatsby-theme-auth0/src/auth/service.ts" rel="nofollow noreferrer">here</a> It's part of <code>gatsby-theme-auth0</code></p>
  <p>EDIT: To clarify, the server does receive the request and sends back <code>{&quot;error&quot;:&quot;jwt malformed&quot;}</code> - which makes sense, since it's <code>undefined</code>.</p>