In React.js, fetching data from APIs is essential. There are various methods to achieve this. Here are some:
Using Fetch API
Use the Fetch API to send HTTP requests. This method is integrated into modern browsers and makes data retrieval easier.
In the first method we will see how we can get data from an API using Fetch API. From this blog I will use JSONPlaceholder.
import { useEffect, useState } from "react";
import "./App.css";
const App = () => {
const [user, setUser] = useState([]);
let URL = "https://jsonplaceholder.typicode.com/users";
// fetch data from api
useEffect(() => {
fetch(URL)
.then((res) => res.json())
.then((data) => setUser(data));
}, []);
return (
<div>
<h1>Fetch API Data Using Fetch API</h1>
{user &&
user.map((singleUser) => {
return (
<div key={singleUser.id}>
<h2>Name: {singleUser.name}</h2>
<p>Email: {singleUser.email}</p>
</div>
);
})}
</div>
);
};
export default App;
Steps to Fetching Data
- Step-1 First we need to create a state variable to store our fetching data.
- Step-2 Then we need to fetch the data using the API link. The fetch() method returns a Promise that resolves to a Response object. Here, we need to get the actual data we can convert the Promise into json data format and then store the data into our state variable.
- Step-3 Finally we can use the data according to our requirement.
Async/Await with Fetch
Use the async/await syntax to perform asynchronous operations, making your code cleaner and more readable.
Second approach
import { useEffect, useState } from "react";
import "./App.css";
const App = () => {
const [user, setUser] = useState([]);
let URL = "https://jsonplaceholder.typicode.com/users";
useEffect(() => {
let fetchApiData = async () => {
let response = await fetch(URL);
let data = await response.json();
console.log(data);
setUser(data);
};
fetchApiData();
}, []);
return (
<div>
<h1>Fetch API Data Using Fetch API</h1>
{user &&
user.map((singleUser) => {
return (
<div key={singleUser.id}>
<h2>Name: {singleUser.name}</h2>
<p>Email: {singleUser.email}</p>
</div>
);
})}
</div>
);
};
export default App;
The difference between the first and second approaches is that we handle data in an asynchronous manner.
Third approach
import { useEffect, useState } from "react";
import "./App.css";
const App = () => {
const [user, setUser] = useState([]);
let URL = "https://jsonplaceholder.typicode.com/users";
useEffect(() => {
const fetchData = async () => {
try {
let response = await fetch(URL);
let data = await response.json();
setUser(data);
} catch (error) {
console.log(error.message);
}
};
fetchData();
}, []);
return (
<div>
<h1>Fetch API Data Using Fetch API</h1>
{user &&
user.map((singleUser) => {
return (
<div key={singleUser.id}>
<h2>Name: {singleUser.name}</h2>
<p>Email: {singleUser.email}</p>
</div>
);
})}
</div>
);
};
export default App;
In this approach we use try catch block so that we can handle errors more efficiently.
Axios Library
Use the Axios library, which is a popular choice for HTTP requests. It includes features such as interceptors and automated JSON data transformation.
Here, in this approach we need to install axios library.
npm i axios
import { useEffect, useState } from "react";
import axios from "axios";
import "./App.css";
const App = () => {
const [user, setUser] = useState([]);
let URL = "https://jsonplaceholder.typicode.com/users";
useEffect(() => {
let fetchData = async () => {
try {
let response = await axios.get(URL);
setUser(response.data);
} catch (error) {
console.log(error.message);
}
};
fetchData();
}, []);
return (
<div>
<h1>Fetch API Data Using Fetch API</h1>
{user &&
user.map((singleUser) => {
return (
<div key={singleUser.id}>
<h2>Name: {singleUser.name}</h2>
<p>Email: {singleUser.email}</p>
</div>
);
})}
</div>
);
};
export default App;
React Query or SWR
Consider using libraries like React Query or SWR, which offer hooks and utilities for fetching, caching and updating asynchronous data in React apps.
// main.jsx file
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import "./index.css";
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
);
// App.jsx file
import React from "react";
import { useQuery } from "@tanstack/react-query";
const App = () => {
let URL = "https://jsonplaceholder.typicode.com/users";
const { data, isLoading } = useQuery({
queryKey: ["user"],
queryFn: () => fetch(URL).then((res) => res.json()),
});
console.log(data, isLoading);
return (
<div className="App">
{isLoading ? (
<h1>No Data Found</h1>
) : (
data.map((user) => (
<div key={user.id}>
<h1>ID: {user.id}</h1>
<h4>Name: {user.name}</h4>
<p>Email: {user.email}</p>
</div>
))
)}
</div>
);
};
export default App;
Conclusion
To summarize, mastering data fetching in React.js is essential for developing dynamic and interactive web applications. Understanding the various methods available allows developers to retrieve data from APIs more efficiently and improve the functionality of their projects.
Top comments (2)
I found React Query is the best
Yes indeed