Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer GET Requests in React with Axios | Getting Started and Making Requests with Axios
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Axios for React Applications

bookGET Requests in React with Axios

To fetch data from an API in your React component, you will often use Axios inside a useEffect hook. This approach ensures that the data is requested when the component mounts. The typical structure involves importing Axios, creating state variables for your data, loading, and error states, and then making the GET request within useEffect. Here is an example of how you might set this up:

import React, { useEffect, useState } from "react";
import axios from "axios";

function UsersList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
  const controller = new AbortController();

  axios
    .get("https://jsonplaceholder.typicode.com/users", {
      signal: controller.signal,
    })
    .then(response => {
      setUsers(response.data);
      setLoading(false);
    })
    .catch(error => {
      if (axios.isCancel(error)) return;
      setError(error.message);
      setLoading(false);
    });

  return () => {
    controller.abort();
  };
}, []);


  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

In this example, the useEffect hook runs only once when the component mounts, because of the empty dependency array. The GET request is made to fetch user data, and the response is used to update the users state. The loading state is set to false after the request finishes, whether it succeeds or fails. The error state captures any errors that occur during the request, allowing you to display an error message if something goes wrong.

When fetching data with Axios, you should carefully manage component state to provide a good user experience. Three state variables are commonly used:

  • A loading state to indicate when data is being fetched;
  • A data state to store the fetched data;
  • An error state to capture and display any errors that occur.

Start with loading set to true, and only set it to false once the request completes (either successfully or with an error). This lets you show a loading indicator while the request is in progress. If the request succeeds, update your data state with the response and clear the error state. If the request fails, set the error state with the error message and clear or leave the data state as appropriate. Always set loading to false in both the success and error cases so your UI updates correctly. This pattern ensures your component accurately reflects the current state of the request and provides clear feedback to users.

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Suggested prompts:

Can you explain how the AbortController works in this example?

What should I do if I want to fetch data from a different API endpoint?

How can I handle multiple API requests in the same component?

bookGET Requests in React with Axios

Veeg om het menu te tonen

To fetch data from an API in your React component, you will often use Axios inside a useEffect hook. This approach ensures that the data is requested when the component mounts. The typical structure involves importing Axios, creating state variables for your data, loading, and error states, and then making the GET request within useEffect. Here is an example of how you might set this up:

import React, { useEffect, useState } from "react";
import axios from "axios";

function UsersList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
  const controller = new AbortController();

  axios
    .get("https://jsonplaceholder.typicode.com/users", {
      signal: controller.signal,
    })
    .then(response => {
      setUsers(response.data);
      setLoading(false);
    })
    .catch(error => {
      if (axios.isCancel(error)) return;
      setError(error.message);
      setLoading(false);
    });

  return () => {
    controller.abort();
  };
}, []);


  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

In this example, the useEffect hook runs only once when the component mounts, because of the empty dependency array. The GET request is made to fetch user data, and the response is used to update the users state. The loading state is set to false after the request finishes, whether it succeeds or fails. The error state captures any errors that occur during the request, allowing you to display an error message if something goes wrong.

When fetching data with Axios, you should carefully manage component state to provide a good user experience. Three state variables are commonly used:

  • A loading state to indicate when data is being fetched;
  • A data state to store the fetched data;
  • An error state to capture and display any errors that occur.

Start with loading set to true, and only set it to false once the request completes (either successfully or with an error). This lets you show a loading indicator while the request is in progress. If the request succeeds, update your data state with the response and clear the error state. If the request fails, set the error state with the error message and clear or leave the data state as appropriate. Always set loading to false in both the success and error cases so your UI updates correctly. This pattern ensures your component accurately reflects the current state of the request and provides clear feedback to users.

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 3
some-alt