title: Fetch in a Web Worker using React
body: <p>I have a React page that asks for a user input for some info and returns an array of JSON objects from an API. </p>
  
  <p>The query can return a large result causing in the page to freeze on loading the fetch, so I wanted to use a web worker to separate the threads and add a loading wheel to allow the user to know the site hasn't crashed.</p>
  
  <p>I currently have my web worker with this code:</p>
  
  <h1><strong>Worker Code</strong></h1>
  
  <pre><code>const self = this;
  
  export default () =&gt; {
      self.addEventListener('message', e =&gt; {
          if (!e) return;
          let query = e.data;
          let res = null;
  
          fetch(`https://statsapi.web.nhl.com/api/v1/schedule?startDate=${query}&amp;endDate=${query}`)
          .then(response =&gt; {
              return response.json();
          })
          .then(function(_ref) {
              postMessage(_ref);
          });
      });
  }; 
  </code></pre>
  
  <p>This is just an example API, but the real API result would be much larger and take a longer time to load. </p>
  
  <p>I am also using <code>function(_ref)</code> instead of <code>({ data }) =&gt;</code> because when processed through babel, <code>({ data }) =&gt;</code> would be turned into <code>_ref.data</code> when there is no data accessor through ref, and <code>_ref</code> works at returning the array. </p>
  
  <p>I have my code implemented in a web worker class like such:</p>
  
  <h1><strong>Worker Constructor</strong></h1>
  
  <pre><code>export default class WebWorker {
      constructor(worker) {
          const code = worker.toString();
          const blob = new Blob(['(' + code + ')()'], { type: 'text/javascript' });
          return new Worker(URL.createObjectURL(blob));
      }
  }
  </code></pre>
  
  <p>I call the webworker in another class as such:</p>
  
  <h1><strong>Web Worker Creation</strong></h1>
  
  <pre><code>componentDidMount = () =&gt; {
      this.worker = new WebWorker(worker);
  }
  
  getInfo = () =&gt; {
      this.worker.postMessage(this.state.query);
  
      this.setState(prevState =&gt; ({
          ...prevState,
          open: true
      }), () =&gt; {
          this.worker.addEventListener('message', (event) =&gt; {
              const res = event.data;
              this.setState({
                  results: res,
                  open: false
              });
          });
      });
  }
  </code></pre>
  
  <p>The issue I have been running into is when I attempt calling it like I am, the web worker doesn't seem to be processing on another thread. The page still freezes even though the web worker is getting the data, as it still sets the state correctly after freezing.</p>
  
  <p>I am new to web workers so is there something that I am missing that would allow it to work or would there be a different way of using a web worker with a fetch?</p>