Step 22
It is easy to use any JavaScript library (available through NPM) in a React app. For example, we will use a library called axios which provides an interface for fetching resources through HTTP requests.
Axios is similar to JavaScript's fetch in functionality. However, it provides a more robust and flexible feature set.
Stop the React app (Ctrl
+ C
in the terminal) and install axios:
npm install axios
Next, import axios
library to the Search.js
file:
import axios from "axios";
Finally, update the fetchDefinitions
method.
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 response = await axios.get(`${dictionaryAPI}${wordToDefine}`);
- const data = await response.json();
+ const data = response.data;
console.log(data[0]);
} catch (err) {
console.log(err);
}
};
Save the file and run the React app. In the browser, test that we can fetch a word's definition as before.