Lesson 6

React.js: Fetching and Displaying Data with Axios

Introduction to Fetching and Rendering Data with Axios

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.

Understanding APIs

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:

JSON
1[ 2 { 3 "id": "412e7655-bcec-44cb-bdf1-9439c357ed04", 4 "text": "It's LeviOsa, Not LeviosAr.", 5 "authorId": "a9f39c40-b073-11ec-b909-0242ac120002", 6 "likesCount": 19 7 }, 8 { 9 "id": "1fa34ced-5817-4273-9df8-07dac2c18b3a", 10 "text": "A robot may not injure a human being or, through inaction, allow a human being to come to harm", 11 "authorId": "382dffad-4988-45c8-912f-c26477ac0d6d", 12 "likesCount": 17 13 } 14]

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.

Introduction to Axios

We can fetch data effortlessly by using Axios, a library for making HTTP requests. You can import Axios into your file like so:

JavaScript
1import axios from 'axios';

We interact with APIs by sending a GET request:

JavaScript
1axios.get('some_api_url').then(response => { 2 // Here is the response from the API 3 console.log(response.data); 4});

With axios.get(), we communicate with the API, and .then() handles the response. If there's an error, we catch and handle it:

JavaScript
1axios.get('some_api_url') 2 .then(response => console.log(response.data)) 3 .catch(error => console.error('Error:', error));

This code logs an error message if one occurs.

Displaying API Data in React

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:

JavaScript
1import React, { useState, useEffect } from 'react'; 2import axios from 'axios'; 3 4function MyComponent() { 5 // Initialize a state variable 'data' and its update function 'setData' 6 const [data, setData] = useState(null); 7 8 useEffect(() => { // Use useEffect to fetch data when component mounts 9 axios.get('some_api_url') 10 .then(response => setData(response.data)) // Update data state 11 .catch(error => console.error('Error:', error)); // Error handling 12 }, []); 13 14 // Render the data or 'Loading...' if data hasn't been fetched 15 return ( 16 <div> 17 {data ? JSON.stringify(data) : 'Loading...'} 18 {/* "condition ? expr1 : expr2" notation is similar to the if ... else statement, it returns `expr1` if the condition is true, and `expr2` otherwise */ } 19 </div> 20 ); 21}

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.

Lesson Summary and Practice

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!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.