Elevate your React app! Explore 5 powerful methods for fetching API data seamlessly in React. Enhance performance and responsiveness with these essential techniques.
When developing applications, you often need to get data from an API. This lets you deliver dynamic and often-updated content within your application.
You'll want to retrieve this data as you may need to interact with external services, communicate with a distant server, or access a database.
In this article, I'll show you different methods of fetching data using React as an example.
API stands for Application Programming Interface. It enables the exchange of information and functionality between different systems, such as between a website and a server or between different software applications.
You can think of an API as being like a restaurant waiter. You don't go inside the kitchen to prepare your meal when you dine at a restaurant. Rather, you inform the waiter of your preferences, and they will take your order to the kitchen team. The kitchen team prepares the food and returns it to the waiter, who then delivers it to your table.
An API functions as a waiter for software applications. It is a set of rules that lets one program ask another for something it needs. It serves as a bridge for software apps to communicate and interact.
There are a few reasons why APIs are important in web development. Let's go over some of them below:
When a web browser or a mobile app sends a message to a server, it's known as an HTTP
request. A HTTP
request involves asking the server for specific data or an action and getting a response. The server responds by interacting with web pages and services.
Using APIs in software development makes things more flexible and efficient. It also enhances security and enables different software systems to work well together.
We use various HTTP
request methods, such as get
, post
, put
, and delete
, to get and store data in our database. But the most common requests made are the get
and post
requests.
Let's discuss the meaning of these HTTP
request methods:
One widely adopted way of checking APIs is through the browser.
Getting a response from an API
To learn more ways to get data, check out this article: Getting Started with Application Programming Interfaces (APIs).
There are various ways to fetch data in React. Before we begin, let’s start by writing some React boilerplate code or by creating a template in our editor.
Here's the command to do that:
npx create-react-app ./ or npx create-vite@latest ./
creating template for our project
After this, type the following command:
npm run dev
This will start the development server.
In the image above, you'll notice that I added a period (.) immediately following the command.
This is a convenient shorthand for creating the template within the current directory.
This method is used to fetch data from a server and is used in React. It manages any issues that may arise when obtaining the data and helps you manage its storage. SWR
includes useState()
and useEffect()
, so there is no need to import them.
SWR
speeds up your app's loading time by showing older data while fetching the latest information.SWR
to get datanpm i swr
useSWR
, which is a hook that has both useState()
and useEffect()
, into your application.fetcher
and assign it a function.This function is capable of receiving any number of arguments, denoted by the ...args
syntax.
The function looks like this:const fetcher = (...args) => fetch(...args).then(res => res.json())
Here is how thenSwr.jsx
should look like:
import useSWR from 'swr';
// Import useSWR from swr package
// created function to handle API request
const fetcher = (...args) => fetch(...args).then((res) => res.json());
const Swr = () => {
const {
data: countries,
error,
isValidating,
} = useSWR('https://restcountries.com/v2/all', fetcher);
// Handles error and loading state
if (error) return <div className='failed'>failed to load</div>;
if (isValidating) return <div className="Loading">Loading...</div>;
return (
<div>
{countries &&
countries.map((country, index) => (
<img key={index} src={country.flags.png} alt='flag' width={100} />
))}
</div>
);
};
export default Swr;
Using swr
Let's see what's going on in the above code:
SWR
library.map()
method to iterate through the list of nations.&&
line to ensure that if there are no issues and the data has been correctly received (meaning the countries
variable is not null or undefined), it will proceed to map over the data and show an image
element for each nation.App.jsx
or Index.jsx
so it could be viewed in the browser.Here's the result:
The result of using Swr
Fetch()
methodThe fetch()
method is well-known for retrieving data from APIs. It is recognized as the simplest and most used approach.
fetch()
methodfetch()
method makes it simple to get information from the internet using JavaScript.fetch()
method supports different HTTP
methods. These methods include get, post, put, and delete. They give you flexibility in interacting with APIs.fetch()
method is a native JavaScript method. You can use it without any external libraries or dependencies. This makes it lightweight and efficient.fetch()
to get datauseState()
for state management in React.useEffect
()
, as it will make the data from the API render.Here is how the Fetch.jsx
should look like:
import { useState, useEffect } from 'react';
const Fetch = () => {
const [photos, setPhotos] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/photos')
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
setPhotos(data);
});
}, []);
return (
<div>
{photos.map((photo) => (
<img key={photo.id} src={photo.url} alt={photo.title} width={100} />
))}
</div>
);
};
export default Fetch;
Using the fetch()
Inside useEffect()
, we fetch our data by sending a request with the API key. The response comes back in JSON (JavaScript Object Notation).
In the return statement, we process the received photos by utilizing a map()
function to iterate through each item.
In our specific scenario, we are only interested in the photos. We render them in the browser by displaying them in the main file of the application, or root. The main file could be App.jsx
or Index.js
.
Here is how the App.jsx
file looks:
The root of the application
And here's the result:
using fetch()
React Query
libraryReact Query
, also known as TanStack Query
, is useful for managing data in React applications. The difference between the two names is the version.
Using React Query is easy and makes handling data in your app feel almost automatic, like it's taking care of things for you. For instance, fetching, caching, synchronizing, and updating server states in your applications.
React Query
methodReact Query
. You can retrieve the same data from the cache again. This saves time by avoiding a new network request.React Query
has optimistic updates that can update the UI. It shows the expected outcome of a mutation without server confirmation. A smoother user experience is achieved as a result.React Query
includes DevTools that offer insights into query, mutation, and caching state. These tools help with debugging and optimizing performance.React Query
to get dataTo begin, use this command to install the React-Query library (TanStack Query) into your application:
npm i @tanstack/react-query
To make things work, use QueryClientProvider
from @tanstack/react-query
.
Wrap your application, which is the Main.jsx
component, with it and pass queryClient
as a prop. It comes automatically from the initialized QueryClient
.
Here is how the Main.jsx
file should look like:
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
)
wrapping root of your application
Now that we have done this, we can fetch the data:
@tanstack/react-query
at the top of your file:import { useQuery } from '@tanstack/react-query';
useQuery hook
is defined with two crucial parameters in object form. These parameters are queryFn
and queryKey
.queryFn
handles fetching data from the endpoint.queryKey
serves as the unique identifier for the data obtained.As mentioned earlier, React Query
simplifies and manages loading states and errors. You don't need a separate useState() hook
.
import { useQuery } from '@tanstack/react-query';
const Query = () => {
const { data: comments, isLoading, error } = useQuery({
queryFn: () =>
fetch('https://jsonplaceholder.typicode.com/comments?_limit=10').then(
(res) => res.json()
),
queryKey: ['comments'],
});
// Show a loading message while data is fetching
if (isLoading) {
return <h2>Loading...</h2>;
}
// to handle error
if (error) {
return <div className="error">Error: error fetching</div>
}
return (
<div>
<h1 className='title'>Email address of users</h1>
{comments.map((comment) => (
<h2 key={comment.id} className="users">
{comment.id}.
{comment.email}
</h2>
))}
</div>
);
};
export default Query;
Code (Query.jsxfile)
Here's the result:
The result from the endpoint
As previously mentioned, useQuery()
manages the loading and error states as long as it's defined.
When your internet service is bad, the browser may show these conditions because it couldn't get the data.
Here's an example:
Loading and Error state
Axios
LibraryAxios is a third library package that we can add to our program to retrieve information from an API. Because Axios is used in both web browsers and server-side JavaScript, it is useful for a wide range of tasks.
Axios
LibraryAxios
into your application like this:npm i axios
Commands for installing the package
Axios
library into your application.useState()
, which enables state management in React.useEffect
()
which facilitates the rendering of data from the API.Here is what the Axios.jsx
file should look like:
import { useEffect, useState } from 'react'
import axios from 'axios'
const Axios = () => {
const [meals, setMeals] = useState([])
useEffect(() => {
axios.get('https://www.themealdb.com/api/json/v1/1/random.php')
.then((res) => {
setMeals(res.data.meals);
})
}, [])
return (
<div>
{meals.map((meal) => (
<img key={meal.idMeal} src={meal.strMealThumb} alt={meal.strMeal} width={400}/>
))}
</div>
code
Inside useEffect()
we fetch our data by sending a request with the API key. The response comes back in JSON (JavaScript Object Notation).
We use a map()
function in the return statement. The map()
function helps us process the meals. It iterates through each piece of information.
In our specific scenario, we are only interested in the images of each meal.
To display them in the browser, we render them in the root of the application, which could be App.jsx
or Index.js
.
Here's the result:
using axios library (Result)
useFetch
custom hook from react-fetch-hookA custom hook in React is a JavaScript function. It is reusable and leverages React's built-in hooks. The purpose is to encapsulate and share logic across multiple components. This promotes code modularity and maintainability.
A custom hook allows us to reuse the fetching logic in various components of our app.
In React, custom hooks are often named with a convention, such as useFetch
. Typically, any custom hook follows a naming pattern that starts with the keyword use
.
npm install react-fetch-hook
Command
useFetch hook
:import useFetch from "react-fetch-hook";
Now, you can use the useFetch
hook to interact with an API.
useFetch hook
. Update the variables.Code example:
import useFetch from "react-fetch-hook";
const UseFetch = () => {
const { data: posts, isLoading, error } = useFetch('https://jsonplaceholder.typicode.com/posts');
// Show a loading message while data is fetching
if (isLoading) {
return <h2>Loading...</h2>;
}
// Handle error
if (error) {
return <div className="error">Error: error fetching</div>;
}
return (
<div>
<h1 className='title'>Post of users</h1>
{posts.map((post) => (
<div key={post.id} className="card">
<h2 className='users'>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
};
Here's the result:
Data called using the custom hook
This article talks about different ways and tools to fetch API data in React.Understanding these methods will assist you in creating advanced applications.
Utilizing React to construct dynamic applications and obtain data from APIs is vital. Many apps rely on data from APIs, so developers need to know the best and quickest ways to get that data.
Whether you're a beginner or experienced developer, every method has its benefits. These benefits can improve your programming skills. They can also help you create reliable apps that use data.
If you found this tutorial helpful, please share it with other developers.
Thank you for reading💖
Source: https://www.freecodecamp.org
#react #reactjs