Hello! Welcome to our seventh lesson in the "Handling Side Effects with useEffect" module.
In our last lesson, we built a solid foundation for fetching data from an API. We learned the core pattern using useEffect and useState, and crucially, how to use an AbortController to handle race conditions during re-fetches. However, our component currently provides a poor user experience: it shows a blank screen while data is loading and offers no feedback if an error occurs.
Today, we'll fix that. This lesson is all about managing the lifecycle of an asynchronous request. You will learn to implement loading and error states to give your users clear, immediate feedback. We'll start with a straightforward approach using multiple state variables and then, leveraging your TypeScript and CS background, we'll explore a more robust, type-safe pattern using discriminated unions to make impossible states unrepresentable.
1. Indicating a Loading State
When a user interacts with your application, they expect a response. If a network request takes a few seconds, a blank or unresponsive UI can make the app feel broken. A loading indicator is essential for a good user experience.
The pattern is simple:
- Create a boolean state variable, let's call it
isLoading. - Set it to
truejust before you initiate thefetchrequest. - Set it to
falseonce the request is complete (whether it succeeded or failed). - Conditionally render a loading message or spinner based on the
isLoadingstate.
This video demonstrates this process clearly.
Fetching Data in React - Complete Tutorial
This first segment from the 'Fetching Data in React - Complete Tutorial' by Cosden Solutions shows how to add a simple isLoading state to your component.
Watch from 06:28 to 09:44. Focus on how a new piece of state (isLoading) is created and how it's toggled before and after the fetch call. Also, note the simple conditional rendering logic used to display the 'Loading' message.
Using finally for Robustness
In the video, setIsLoading(false) was called after the data was successfully set. But what happens if the request fails? The component would get stuck in a loading state forever.
To solve this, we can use a try...catch...finally block. The finally block guarantees that its code will execute regardless of whether the try block succeeded or the catch block was triggered. This makes it the perfect place to set loading to false.
The next part of the video explains this exact refinement.
Fetching Data in React - Complete Tutorial
Now, let's see how to make our loading state more robust. This short clip explains why moving the setIsLoading(false) call into a finally block is a best practice.
Watch from 14:14 to 15:35. The key takeaway here is understanding that the finally block ensures the loading state is always reset, preventing your UI from getting stuck.
2. Handling Fetch Errors
Just as we need to handle the loading state, we must also handle potential errors. Network requests can fail for many reasons: the server might be down, the user might lose internet connection, or the requested resource might not exist.
The try...catch block is our tool for this. We'll add another piece of state to hold a potential error object.
- Create a state variable for the error, e.g.,
error, initialized tonull. - Wrap your
fetchlogic in atryblock. - In the
catch(e)block, update your error state with the caught error object. - Conditionally render an error message if the
errorstate is notnull.
This video walks through the implementation.
Fetching Data in React - Complete Tutorial
The same video provides a clear guide on adding error handling using a try...catch block and a new error state variable.
Watch from 09:44 to 14:14. Pay attention to how the try...catch block is structured and how the setError function is used within the catch block. The presenter also discusses TypeScript typing for the error object.
3. A Critical Nuance: HTTP Status Codes and fetch
There's a major gotcha with the browser's fetch API that trips up many developers. A fetch() promise only rejects when a network error occurs (e.g., the server is unreachable). It does not reject for HTTP error statuses like 404 Not Found or 500 Internal Server Error.
This means that if you request a non-existent URL, fetch will "succeed," and your code will proceed to the await response.json() line, which will likely fail because the response body isn't valid JSON. Your catch block will catch that error, but the error message (SyntaxError: Unexpected token...) will be misleading.
The correct way to handle this is to manually check the response status. The response object has an ok property, which is true if the HTTP status is in the 200-299 range. If response.ok is false, we should throw our own Error.
The following video explains this crucial concept.
Full React Tutorial #19 - Handling Fetch Errors
This video from Net Ninja provides an excellent explanation of the different types of fetch errors and how to correctly handle HTTP error statuses.
Watch from 01:56 to 07:39. This is a dense and important segment. Focus on: Checking response.ok: How to check this property and throw new Error() to trigger the catch block for HTTP errors (01:56 - 05:30). State Updates: How setError and setIsPending(false) are called from the catch block (05:17 - 06:52). Resetting State: The importance of setting the error back to null on a subsequent successful fetch (06:52 - 07:39).
Consolidated Code Example
Let's put everything together into a single component. This example fetches a post based on an id.
import React, { useState, useEffect } from 'react';
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
function PostViewer({ id }: { id: number }) {
const [post, setPost] = useState<Post | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
// We don't want to fetch if the component is just initializing without a valid ID
if (!id) return;
const fetchPost = async () => {
// Reset states for a new fetch
setIsLoading(true);
setError(null);
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
// This is the crucial check for HTTP errors!
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: Post = await response.json();
setPost(data);
} catch (e) {
// Ensure we're setting an Error object
if (e instanceof Error) {
setError(e);
} else {
setError(new Error('An unknown error occurred'));
}
} finally {
// This runs regardless of success or failure
setIsLoading(false);
}
};
fetchPost();
}, [id]); // Re-fetch whenever the id prop changes
// The order of these checks is important for the UI logic
if (isLoading) {
return <div>Loading post...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
if (!post) {
return <div>No post found.</div>;
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
Test your understanding!
Imagine you have the code above. If the server responds with a 404 Not Found status code, which line of code will be the first to set a state variable, and what will its value be?
Show answer
The first state-setting line to execute will be setError(new Error('HTTP error! status: 404')).
Here's the flow:
fetchresolves successfully because a response was received from the server.- The
if (!response.ok)check evaluates totruebecause a 404 status is not "ok". throw new Error(...)is executed.- The
tryblock is exited, and thecatch (e)block is entered. setError(e)is called with theErrorobject we just threw.
4. A More Robust Pattern: Discriminated Unions
The approach using isLoading, error, and data states works, but it has a subtle flaw. It's possible to represent "impossible" states. For example, what would it mean if isLoading was true and error was also not null? Or if we had data but isLoading was also true? While our logic prevents this, the type system doesn't.
A more advanced and type-safe pattern, especially powerful in TypeScript, is to use a discriminated union. We can model our component's asynchronicity as a state machine with one single state object.
This pattern is beautifully explained in the following article.
Loading States and Error Handling
This article from Steve Kinney's 'React with TypeScript' course introduces a superior pattern for handling async states. It first highlights the problem with boolean flags and then presents the elegant solution using discriminated unions.
Please read the sections 'The Problem with Boolean Flags' and 'Discriminated Unions: Making Impossible States Impossible'. Pay close attention to the critique of the boolean approach and the examples of impossible states it allows. Study the TodosState type definition. Understand how the status property acts as the 'discriminant' that tells TypeScript which other properties (data or error) are available. Notice how the rendering logic simplifies into a switch statement, and how TypeScript can enforce that you handle every possible case.
Implementing the Discriminated Union Pattern
Let's refactor our PostViewer component to use this superior pattern.
import React, { useState, useEffect } from 'react';
interface Post {
id: number;
title: string;
body: string;
}
// 1. Define the discriminated union type for our async state
type PostState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: Post }
| { status: 'error'; error: Error };
function PostViewerWithUnion({ id }: { id: number }) {
// 2. Use a single state variable
const [state, setState] = useState<PostState>({ status: 'idle' });
useEffect(() => {
if (!id) {
setState({ status: 'idle' });
return;
}
const fetchPost = async () => {
// 3. Set state based on the state machine transitions
setState({ status: 'loading' });
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: Post = await response.json();
setState({ status: 'success', data });
} catch (e) {
const error = e instanceof Error ? e : new Error('Unknown error');
setState({ status: 'error', error });
}
};
fetchPost();
}, [id]);
// 4. Use a switch statement for clean, type-safe rendering
switch (state.status) {
case 'idle':
return <div>Please provide an ID to fetch a post.</div>;
case 'loading':
return <div>Loading post...</div>;
case 'error':
// TypeScript knows `state.error` exists in this case
return <div>Error: {state.error.message}</div>;
case 'success':
// TypeScript knows `state.data` exists in this case
return (
<div>
<h1>{state.data.title}</h1>
<p>{state.data.body}</p>
</div>
);
}
}
This approach is cleaner, less prone to bugs, and leverages the full power of TypeScript to help you write correct code. When you try to access state.data in the 'error' case, TypeScript will immediately give you a compiler error, preventing a whole class of runtime bugs.
Conclusion
In this lesson, we significantly improved the robustness and user experience of our data-fetching components. You now have the tools to handle the entire lifecycle of an asynchronous request gracefully.
Key Takeaways:
- Always provide feedback to the user during asynchronous operations using loading states.
- Handle potential failures gracefully by implementing error states.
- The
finallyblock is the best place to reset loading indicators, as it runs after both success and failure. - The
fetchAPI requires you to manually checkresponse.okto handle HTTP errors (like 404 or 500). - For highly robust and type-safe components, prefer a discriminated union to model your asynchronous state machine over multiple boolean flags.
We've covered a lot of ground on useEffect for side effects. In our next and final lesson for this module, we will consolidate our knowledge by looking at how to identify and fix common pitfalls with useEffect, such as the dreaded infinite re-render loop.