Step 21

We want to fetch the definition of a word when the user clicks on the "Define" button. Update the <button> element and give it anonClick attribute as follows.

    <button 
      className="button is-info is-large" 
      id="define-btn"
+     onClick={this.fetchDefinitions}
    >
      Define
    </button>

Let's define the fetchDefinitions method:

fetchDefinitions = (event) => {
  event.preventDefault();
  const dictionaryAPI = "https://api.dictionaryapi.dev/api/v2/entries/en_US/";
  const wordToDefine = this.state.word;
  fetch(`${dictionaryAPI}${wordToDefine}`)
    .then((response) => response.json())
    .then((data) => console.log(data[0]))
    .catch((err) => console.log(err));
};

Save the file and visit the running app in the browser. Open the console in the Developer Tools. Try to search for the definition of a word.

Note we can easily update the syntax to use async/await, as follows:

fetchDefinitions = async (event) => {
  event.preventDefault();
  const dictionaryAPI = "https://api.dictionaryapi.dev/api/v2/entries/en_US/";
  const wordToDefine = this.state.word;
  try {
    const response = await fetch(`${dictionaryAPI}${wordToDefine}`);
    const data = await response.json();
    console.log(data[0]);
  } catch (err) {
    console.log(err);
  }
};