Type-Safe API Fetching with React Query and TypeScript
Show how to define a type for the API response and use it in a `useQuery` hook to fetch data in a type-safe manner.
import { useQuery } from '@tanstack/react-query';
// Define TypeScript type for API response
type Post = {
id: number;
title: string;
body: string;
};
// Async function to fetch data from the API
const fetchPosts = async (): Promise<Post[]> => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
First, we import `useQuery` from the `@tanstack/react-query` package. We define a TypeScript type `Post` to describe the structure of the data we expect to receive from the API. Then, we declare an asynchronous function `fetchPosts` that fetches data from a sample API and returns it as a JSON object, ensuring the response matches the `Post[]` type.
const { data, error, isLoading } = useQuery<Post[], Error>(['posts'], fetchPosts);
Here, we make use of the `useQuery` hook to fetch the posts. The first parameter is the unique key for the query (in this case, 'posts'), and the second parameter is the fetch function. The hook returns an object containing the `data`, potential `error`, and a boolean `isLoading` state that can be used to handle loading and error states in the UI. The type annotations `Post[]` and `Error` ensure that the data and error are properly typed.