title: React - Fetch from external API function on button click
body: <p>I'm trying to start an API call from a component when a user clicks a button. One URL param depends on the word a user selected before clicking the button. The fetch function is in an external function. When I call the function on button click and console log the result, it shows <code>undefined</code>, probably because of the async nature of the function. </p>
  
  <p>How can I solve this if I want to put the fetch response into the <code>App</code> component state?</p>
  
  <pre><code>import { fetchAPI } from '../fetchAPI';
  
  export default class App extends Component {
  
  constructor() {
      super();
      this.toggleButtonState = this.toggleButtonState.bind(this);
      state = { ... }
  }
  
  toggleButtonState() {
      let selectedWord = window.getSelection().toString();
      fetchAPI(selectedWord);
      // call the fetchAPI function and put the result into state
  }
  
  export function fetchAPI(param) {
      // param is a highlighted word from the user before it clicked the button
      fetch('https://api.com/?param=' + param)
      .then(function(result) {
          return result;
      });
   }
  </code></pre>