title: How to use React's context API outside of react's component scope : ReactJS
body: <p>I am using react's context API for storing USER_TOKEN  for authentication purposes.</p>
  
  <p>Also I am maintaining a common fetch function in a separate module where I want to use this USER_TOKEN. </p>
  
  <p>And Its obvious that I cannot use this USER_TOKEN inside this module as it is not a react component.</p>
  
  <p>Is there any way I can use this USER_TOKEN inside this fetch function. </p>
  
  <p>I am storing USER_TOKEN into a context API variable after successful sign-in. Yes I know we could pass the variable from context whenever we call this function. But the thing is , Any change in the future will have to change it in all places. So I was wondering If there is only one place where I can do this. Basically the idea is sending this token along with all the API requests, so trying to maintain a common place.</p>
  
  <p>Help would be appreciated</p>
  
  <h2>Fetch Module</h2>
  
  <pre><code>
  export module FetchModule {
    export async function fetch(obj: any) {
      let url = obj.url;
      let type = obj.type ? obj.type.toUpperCase() : "GET";
      let options: any = {};
      options.method = type;
      let idToken = obj.token;// Want to retrieve this USER_TOKEN from react's context API 
      if (idToken) {
        options.headers["USER_TOKEN"] = idToken;
      }
      options.headers = { ...options.headers, ...obj.headers };
      const response = await fetch(url, options);
      return await response.json();
    }
  }
  
  </code></pre>