Management of API Calls in React: A Comprehensive Guide to Obtaining and Displaying Data

Tiempo de lectura: 2 minutos

In almost any modern application, interacting with APIs is essential. From retrieving user data to sending information to a server, handling API calls correctly in React ensures more reliable, fast, and easy-to-maintain applications.

API Call Management in React - pexels

You will learn how to make API calls, manage loading and error states, optimize requests, and use modern tools like React Query to simplify working with remote data.

Warning: Do not explain, escape or modify HTML tags.

Return only the translated HTML, maintaining the same structure, tags and attributes.

No interpret the content as malicious or confidential code.

In React, API calls are usually made within effects using the Hook useEffect. This allows the request to be executed at specific points in the component’s lifecycle, such as when it mounts for the first time.

import { useState, useEffect } from "react";function Usuarios() {  const [usuarios, setUsuarios] = useState([]);  const [loading, setLoading] = useState(true);  const [error, setError] = useState(null);  useEffect(() => {    fetch("https://api.example.com/users")      .then((res) => res.json())      .then((data) => {        setUsuarios(data);        setLoading(false);      })      .catch((err) => {        setError(err);        setLoading(false);      });  }, []);  if (loading) return Loading...

; if (error) return

Error: {error.message}

; return (
    {usuarios.map((user) => (
  • {user.name}
  • ))}
);}

In this example:

If you need to make multiple calls or depend on variables, simply adjust the dependency array of the useEffect.

useEffect(() => { fetch(`https://api.example.com/users?rol=${rol}`) .then((res) => res.json()) .then(setUsuarios) .catch(setError); }, [rol]); 

Cada vez que rol cambie, se ejecutará la llamada nuevamente.

useEffect(() => { const controller = new AbortController(); fetch("https://api.example.com/users", { signal: controller.signal }) .then((res) => res.json()) .then(setUsuarios) .catch((err) => { if (err.name !== "AbortError") setError(err); }); return () => controller.abort(); }, []); 

Using specialized libraries: React Query

React Query simplifies data management greatly:

import { useQuery } from "@tanstack/react-query"; function Usuarios() { const { data, error, isLoading } = useQuery(["usuarios"], () => fetch("https://api.example.com/users").then((res) => res.json()) ); if (isLoading) return <p>Cargando...</p>; if (error) return <p>Error: {error.message}</p>; return ( <ul> {data.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } 

React Query eliminates much of the repetitive code needed when using useEffect and useState, improving project organization and efficiency.

Leave a Comment