title: Setting ReactJS state from 3rd party JS file onload
body: <p>I'm basically trying to do this from within a <code>componentWillMount()</code> function of a React component class.</p>
  
  <pre><code>    const script = document.createElement("script");
  
      script.src = "https://apis.google.com/js/client.js";
      script.async = true;
      script.onload = function() {
        gapi.client.setApiKey(API_KEY);
        gapi.client.load('youtube', 'v3');
        this.setState({ gapiReady: true }); 
        // ^ Doesn't work because `this` refers to the script rather than the component itself.
      };
  
      document.body.appendChild(script);
  </code></pre>
  
  <p>Entire component pasted here for completeness:</p>
  
  <pre><code>import React, { Component } from 'react';
  import VideoPlayer from '../../components/VideoPlayer/VideoPlayer';
  import VideoInfo from '../../components/VideoInfo/VideoInfo';
  import SearchBox from '../../components/SearchBox/SearchBox';
  import './App.css';
  
  class App extends Component {
    constructor(props, context) {
      super(props, context);
      this.state = {};
    };
  
    componentWillMount() {
      const script = document.createElement("script");
  
      script.src = "https://apis.google.com/js/client.js";
      script.async = true;
      script.onload = function() {
        gapi.client.setApiKey(API_KEY);
        gapi.client.load('youtube', 'v3');
        this.setState({ gapiReady: true }); // Doesn't work because `this` refers to the script rather than the component
      };
  
      document.body.appendChild(script);
    };
  
    render() {
      if (this.state.gapiReady) {
        return (
          &lt;div className="wrap"&gt;
            &lt;div className="sidebar"&gt;
              &lt;SearchBox /&gt;
              &lt;VideoInfo videoId="vkRDOcma9Qk" /&gt;
            &lt;/div&gt;
            &lt;div className="content"&gt;
              &lt;VideoPlayer /&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        );
      } else {
        return (
          &lt;div&gt;Loading...&lt;/div&gt;
        )
      }
    };
  }
  
  export default App;
  </code></pre>
  
  <p>My goal is to only render the VideoInfo and VideoPlayer components in the render() function when the script has fully loaded, because otherwise code on this components will fail since they rely on the script having been loaded.</p>
  
  <p>Am I going about this the wrong way?</p>