Creating custom API Hooks
We can also create Hooks for the various API calls. Putting these Hooks in a single file allows us to adjust the API calls easily later on. We are going to prefix our custom API Hooks with useAPI so it is easy to tell which functions are API Hooks.
Extracting custom API Hooks
Let’s create custom Hooks for our API now by following these steps:
- Copy the
Chapter12_2folder to a newChapter12_3folder by executing the following command:$ cp -R Chapter12_2 Chapter12_3 - Open the new
Chapter12_3folder in VS Code. - Create a new
src/hooks/api.jsfile. - Edit
src/hooks/api.jsand import the following functions:import { useSuspenseQuery, useMutation } from '@tanstack/react-query' import { fetchPosts, fetchPost, searchPosts, createPost, queryClient, } from '@/api.js' - Define a function to fetch posts, copied over from the code we had in
src/components/post/PostFeed...