Skip to main content

15.2 - Loading and Error States

When working with tRPC on the client side, handling loading and error states effectively is crucial for providing a smooth user experience. React Query, which tRPC integrates with, provides robust tools to manage these states.

Handling Loading/Error States

In tRPC, loading states indicate that data is being fetched or a mutation is in progress. React Query’s hooks provide a isLoading or isFetching state to help you manage this.

Error handling is crucial for providing feedback and handling cases where something goes wrong. React Query’s hooks provide a isError state to help you manage this.

Example: Handling Loading/Errors with useQuery

// src/components/UserProfile.tsx
import { trpc } from "../utils/trpc";

const UserProfile = ({ id }: { id: string }) => {
const {
data: user,
isLoading,
isError,
error,
} = trpc.user.getUser.useQuery(id);

if (isLoading) {
return <div>Loading...</div>;
}

if (isError) {
return <div>Error: {error.message}</div>;
}

return (
<div>
<h1>{user?.name}</h1>
<p>{user?.email}</p>
</div>
);
};

export default UserProfile;

In this example:

  • isLoading is true while the query is fetching data, and you can show a loading indicator.
  • isError is true if an error occurred during the query.
  • error.message provides the error message which you can display to the user.
tip

For mutations, React Query provides similar hooks and states to manage loading and error conditions with useMutation.