How to use react setState with chrome API
<p>I want to use react's <code>setState</code> with chrome API but I'm running into an issue...</p>

<pre><code>componentDidMount() {

    chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.setState({sourceCode: request.source});
        }
    }); 
}
</code></pre>

<p>I tried the following but chrome API does not recognize <code>setState</code> as a function, so then I tried to first save <code>request.source</code> as a variable...</p>

<pre><code>componentDidMount() {
    var source = "";
    chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            source = request.source;
        }
    });
    this.setState({sourceCode: source});
}
</code></pre>

<p>But when I try the following, <code>source</code> remains an empty string. I cannot figure out why since <code>source</code> is being set to <code>request.source</code>. How can I fix this?</p>

<p><strong>EDIT</strong></p>

<p>I am calling a script as so...</p>

<pre><code>chrome.tabs.executeScript(null, {
        file: 'src/js/scripts/getPageSource.js'
     }, function() {
     ...
</code></pre>

<p>and inside the script I have the following...</p>

<pre><code>chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});
</code></pre>

<p>Where <code>DOMtoString</code> function simply returns a string. It is the caught by my <code>componentDidMount</code> which I have verified by printing to the console inside the if statement.</p>

<p>It has come to my attention that the <code>addListener</code> is asynchronous. Is there any way I can save the result in the state?</p>