react-query-boundary
v1.0.0
Published
A simple, reusable React component to handle loading and error states for @tanstack/react-query.
Maintainers
Readme
React Query Boundary A simple, reusable React component to declaratively handle loading and error states for @tanstack/react-query, cleaning up your component logic.
The Problem When you use @tanstack/react-query, you often find yourself writing the same conditional logic over and over again in your components:
function UserProfile({ userId }) { const { data, isLoading, isError, error } = useQuery({ queryKey: ['user', userId], queryFn: () => fetchUser(userId), });
if (isLoading) { return ; }
if (isError) { return ; }
return ( {data.name} {data.email} ); }
This boilerplate clutters your components and mixes state handling with your final UI.
The Solution is a simple wrapper component that handles this logic for you, leaving your component clean and focused on the "success" state.
import { useQuery } from '@tanstack/react-query'; import { QueryBoundary } from 'react-query-boundary';
// Assume fetchUser is defined elsewhere and imported import { fetchUser } from './api';
function UserProfile({ userId }) { const userQuery = useQuery({ queryKey: ['user', userId], queryFn: () => fetchUser(userId), });
return ( <QueryBoundary query={userQuery} loadingFallback={} errorFallback={error => } > {data => ( {data.name} {data.email} )} ); }
Installation npm install react-query-boundary
API Props query (required): The result object returned directly from the useQuery hook.
loadingFallback (required): The JSX to render while the query is initially loading (isPending).
errorFallback (required): A function that receives the error object and should return JSX to render.
children (required): A function that receives the successful data and should return JSX to render.
