title: How prevent fetch request before auth token is received in React Js?
body: <p>I have a separate fetch request function that logins user and saves auth token to localStorage, then my data request fetch should be send with that saved token bearer, but data fetch doesn't wait for token and receives Unauthorized access code.</p>
  <p>My data request fetch looks like this :</p>
  <pre><code>
  // to check for fetch err
  
  function findErr(response) {
      try {
          if (response.status &gt;= 200 &amp;&amp; response.status &lt;= 299) {
              return response.json();
          } else if (response.status === 401) {
              throw Error(response.statusText);
          } else if (!response.ok) {
              throw Error(response.statusText);
          } else {
              if (response.ok) {
                  return response.data;
              }
          }
      } catch (error) {
          console.log(&quot;caught error: &quot;, error);
      }
  }
  
  
  
  const token = JSON.parse(localStorage.getItem(&quot;token&quot;));
  
  // actual fetch request
  
  export async function getData() {
      const url = `${URL}/data`;
  
      var obj = {
          method: &quot;GET&quot;,
          headers: {
              Accept: &quot;application/json&quot;,
              &quot;Content-Type&quot;: &quot;application/json&quot;,
              Authorization: &quot;Bearer &quot; + `${token}`,
          },
      };
  
      const data = await fetch(url, obj)
          .then((response) =&gt; findErr(response))
      
          .then((result) =&gt; {
              return result.data;
          });
  
      return data;
  }
  
  
  </code></pre>
  <p>My fetch requests are in a different js file, I'm importing them in my components like this:</p>
  <pre><code>import React, { useState, useEffect } from &quot;react&quot;;
  
  
  function getInfo() {
  
  const [info, setInfo] = useState()
  
  const importGetDataFunc = async () =&gt; {
          const data = await getData();
  
          setInfo(data);
      };
  
  useEffect(() =&gt; {
          importGetDataFunc();
      
      }, []);
      return (
          &lt;div&gt;
              
          &lt;/div&gt;
      )
  }
  
  export default getInfo
  
  
  </code></pre>
  <p>Now when I go to the getInfo component after login at first fetch request returns 401, but after I refresh the page fetch request goes with token bearer and data gets returned. My problem is that I don't know how to make getData() fetch request to wait until it gets token from localStorage or retry fetch request on 401 code. I tried to implement if statement like this</p>
  <pre><code>
  useEffect(() =&gt; {
  
  if(token){
          importGetDataFunc();
  }
      }, []);
  
  </code></pre>
  <p>where useEffect would check if token is in localStorage and only then fire fetch request, but it didn't work. Any help on how I can handle this would be greatly appreciated.</p>