Data Fetching & APIs
8 min read
Course: React
Topic: Data Fetching & APIs
Hey there, aspiring React developer! π Welcome to a super important topic: grabbing data from the outside world and displaying it in your awesome React apps. Think about it, most modern applications, from your favorite social media feed to the weather app you check every morning, are all about fetching and showing data. Let's dive in and become data-fetching wizards! π§ββοΈ
1. Fetching Data with the Native fetch API
The What and The Why
Definition: The fetch API is a modern, promise-based JavaScript API for making network requests to a server. It's built right into the browser, so you don't need to install any extra libraries to use it.
The Problem: Your React component is like a cozy little house, but it doesn't have all the information it needs inside. It needs to get data from the outside world, like from a server that has a list of users, products, or cat pictures. π How do we do that?
The Solution: We use fetch to send a request to a specific URL (an API endpoint) and get a response back with the data we need.
Let's Get Our Hands Dirty π»
Imagine we want to display a list of users from a fake online API. Hereβs how you'd typically do it in a React component.
We'll use two key React hooks here:
useState: To store the data we get from the API.useEffect: To perform the data fetching "side effect" after our component has rendered.
import React, { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
// We are calling fetch inside useEffect to prevent it from running on every render.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json()) // The response from fetch is a Response object. We need to call .json() to parse the body as JSON.
.then(data => setUsers(data)) // Now we have the actual data, so we update our state.
.catch(error => console.error('Error fetching data: ', error));
}, []); // The empty dependency array [] means this effect will only run once, after the initial render.
return (
<div>
<h1>User List</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default UserList;Under the Hood: When the UserList component first mounts (gets added to the DOM), the useEffect hook runs. It calls fetch with the API endpoint URL. fetch returns a Promise. The first .then() block takes the Response object and parses it as JSON, which also returns a promise. The second .then() receives the actual data and updates the users state. Once the state is updated, React re-renders the component, and this time, users is an array of user objects, which we then map over to display a list of names.
Fun Fact: Before fetch, the go-to way to make network requests in JavaScript was with XMLHttpRequest (XHR). Let's just say fetch is a much cleaner and more pleasant way to do things. You're welcome, future you!
2. Handling Loading and Error States in the UI
The What and The Why
The Problem: What happens while we're waiting for the data to arrive? And what if something goes wrong, like the server is down or our internet connection is spotty? π€ Our users will just see a blank screen or a broken app, which is a terrible user experience.
The Solution: We need to let our users know what's going on by showing them loading indicators and clear error messages.
Let's See It in Action π¬
We can introduce two more state variables to track the loading and error states.
import React, { useState, useEffect } from 'react';
function UserListWithStates() {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(true); // Start with loading as true
const [error, setError] = useState(null); // No error initially
useEffect(() => {
setIsLoading(true); // Set loading to true before we start fetching
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok'); // Handle bad responses
}
return response.json();
})
.then(data => {
setUsers(data);
setIsLoading(false); // Data has been fetched, so set loading to false
})
.catch(error => {
setError(error); // If an error occurs, save it in the state
setIsLoading(false); // Also stop loading
});
}, []);
if (isLoading) {
return <div>Loading users... β³</div>;
}
if (error) {
return <div>Error: {error.message} π</div>;
}
return (
<div>
<h1>User List</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default UserListWithStates;This is a very common pattern in React. We use conditional rendering to show different UI elements based on the current state. It's like having a traffic light for our data:
- Green light (data is here): Show the user list.
- Yellow light (loading): Show a "Loading..." message.
- Red light (error): Show an error message.
3. Abstracting Fetch Logic into Custom Hooks
The What and The Why
The Problem: Our UserListWithStates component is getting a bit crowded with all that data fetching logic. Now, imagine you have another component that needs to fetch a list of posts, and another one for comments. You'd have to repeat all that useState and useEffect logic for loading, error, and data states everywhere! π± That's not very DRY (Don't Repeat Yourself).
The Solution: We can create a reusable custom hook that encapsulates all this logic. A custom hook is just a JavaScript function whose name starts with "use" and that can call other hooks.
Let's Create a useFetch Hook π οΈ
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setIsLoading(true);
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
setData(data);
setIsLoading(false);
})
.catch(error => {
setError(error);
setIsLoading(false);
});
}, [url]); // Re-run the effect if the URL changes
return { data, isLoading, error };
}
export default useFetch;Now, our UserList component becomes incredibly clean and focused on just displaying the data.
import React from 'react';
import useFetch from './useFetch'; // Assuming you saved the hook in this file
function UserListCustomHook() {
const { data: users, isLoading, error } = useFetch('https://jsonplaceholder.typicode.com/users');
if (isLoading) {
return <div>Loading users... β³</div>;
}
if (error) {
return <div>Error: {error.message} π</div>;
}
return (
<div>
<h1>User List</h1>
<ul>
{users && users.map(user => ( // Check if users is not null before mapping
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default UserListCustomHook;Look at that! So much cleaner. Now you can use this useFetch hook in any component to fetch data from any URL. That's the power of custom hooks!
4. Modern Data Fetching: Introduction to React Query / SWR
The What and The Why
The Problem: Our useFetch hook is pretty cool, but modern web applications have more complex needs. What about caching data so we don't have to re-fetch it every time? Or re-fetching data automatically when the user re-focuses the browser tab? Or handling complex state management with pagination and mutations (like adding or deleting data)? Our simple hook can't handle all of that without becoming a monster of complexity.
The Solution: Libraries like React Query (now known as TanStack Query) and SWR were created to solve these problems out of the box. They provide you with powerful hooks that handle caching, background refetching, and much more, with very little configuration.
Let's take a peek at React Query.
Getting Started with React Query
First, you'll need to install it.
npm install @tanstack/react-query
# or
yarn add @tanstack/react-queryNext, you need to wrap your application with a QueryClientProvider. You typically do this in your index.js or App.js file.
// In your main App file
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import UserListReactQuery from './UserListReactQuery';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<UserListReactQuery />
</QueryClientProvider>
);
}
export default App;Fetching Data with useQuery
Now, let's refactor our UserList component one last time using React Query's useQuery hook.
import React from 'react';
import { useQuery } from '@tanstack/react-query';
const fetchUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
function UserListReactQuery() {
const { data: users, error, isLoading } = useQuery({
queryKey: ['users'], // A unique key for this query
queryFn: fetchUsers, // The function that will fetch the data
});
if (isLoading) {
return <div>Loading users... β³</div>;
}
if (error) {
return <div>Error: {error.message} π</div>;
}
return (
<div>
<h1>User List (with React Query!)</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default UserListReactQuery;What's Happening Here?
useQuerytakes an object with aqueryKeyand aqueryFn.- The
queryKeyis used internally by React Query to cache the data. If you use the same key elsewhere, it will return the cached data instantly! - The
queryFnis the asynchronous function that does the actual fetching. - It returns an object with all the states we need:
data,isLoading,error, and many more helpful ones!
React Query and SWR are industry standards for a reason. They take care of so much complexity behind the scenes, allowing you to focus on building your application. For any serious React project, using one of these libraries is highly recommended.
Interesting Fact: The name SWR comes from stale-while-revalidate, which is a caching strategy. It means the library will first return the stale (cached) data, and then in the background, it will re-fetch the data to see if there are any updates. This makes your app feel incredibly fast!
π Extra Reading & References
Challenge
Challenge
Your task is to implement a custom React hook named useFetch that encapsulates data fetching logic, including loading and error states.
Requirements:
- Create a function
useFetchthat accepts one argument:url(a string). - The hook must initialize and manage three pieces of state:
data: The fetched data. Initialize it tonull.isLoading: A boolean to indicate if a fetch is in progress. Initialize it totrue.error: An object to hold any error that occurs. Initialize it tonull.
- Use the
useEffecthook to perform the data fetching operation using the nativefetchAPI. - This effect should only run when the component mounts and whenever the
urlprop changes. - Inside your effect, handle the asynchronous
fetchcall.- Upon successful completion, parse the response as JSON and update the
datastate. - If any error occurs during the fetch or parsing, catch it and update the
errorstate. - Regardless of success or failure, set the
isLoadingstate tofalseonce the operation is complete.
- Upon successful completion, parse the response as JSON and update the
- The hook must return an object with the keys
data,isLoading, anderror.
Expected result
Your code should be a complete implementation of the useFetch custom hook. It must correctly use the useState and useEffect hooks to manage the entire data fetching lifecycle. The function should accept a url, perform a fetch request, and correctly update the data, isLoading, and error states based on the outcome of the request. The final implementation should return an object structured as { data, isLoading, error }.