Welcome! Today, we will learn how our React apps can fetch data from servers using a library known as Axios. Simply put, Axios helps us request information from other applications (servers) through APIs or the Application Programming Interface.
APIs are sets of guidelines that allow communication between software. They often send and receive data in a format called JSON, which stands for JavaScript Object Notation. An API response may look like:
Remember, when working with JSON data from APIs, it might come as an array of objects, or sometimes just a single object. 😊 Always check the structure of the data you receive and adjust your code accordingly!
You can check the structure of the data returned from the API by going to API link in your browser. Try going to "https://api-regional.codesignalcontent.com/posting-application-2/posts/"
to inspect the structure of the data we will be using in this lesson. You will see that the API returns a JSON object that is an array of objects, each object including
the keys id
, text
, authorId
, and likesCount
.
We can fetch data effortlessly by using Axios, a library for making HTTP requests. You can import Axios into your file like so:
We interact with APIs by sending a GET
request:
With axios.get()
, we communicate with the API, and .then()
handles the response. If there's an error, we catch and handle it:
This code logs an error message if one occurs.
Once we have our data, we store it in our component's state and then display it. We use the useState
hook from our previous lessons to store the data, and useEffect
to fetch data when our component loads:
useEffect
takes in 2 parameters. The first is the code to run, and the 2nd is an array of state variables that will trigger the code to run when that state variable is changed. If the array is empty, the code runs once when the component is first mounted to the DOM.
Kudos to you! We've learned about APIs, how to use Axios to fetch data, error handling, and how to display fetched data in React. Time for some practice to solidify what you've learned. You're well on your way to becoming a React wizard!
