I created custom hooks for get requests from the server. Below is an example
const usePost = (id: string) => {
return useQuery(['posts', id], () => getPost(id))
}
const usePosts = () => {
return useQuery(['posts'], () => getPosts())
}
However, I sometimes need to call multiple queries in a single file, so I would like to use the useQueries hook along with the custom hooks. But when I try to use the custom hooks as the queryFn, React throws me an error saying I can't call a hook inside the function 'queryFn'.
const queries = useQueries([
{
queryKey: 'posts',
queryFn: () => usePosts
},
{
queryKey: ['post', id],
queryFn: () => usePost(id)
}
])
// Failed to compile, 'usePost' is called in function 'queryFn' that is neither a React component nor custom hook
How would we be able to use useQueries with custom query hooks?
This is simply a restriction by the Rule of Hooks in React, that hooks can only be called inside React function components and other React custom hooks.
There are two options to overcome this issue in my opinion:
usePost and usePosts in another custom hook// useAllPosts.js
const useAllPosts = (id: string) => {
const { data: post } = usePost(id);
const { data: posts } = usePosts();
return {
post,
posts
}
}
// usePost.js
export const fetchPost = (id: string) => getPost(id);
const usePost = (id: string) => {
return useQuery(['posts', id], fetchPost)
}
// usePosts.js
export const fetchPosts = () => getPosts();
const usePosts = () => {
return useQuery(['posts'], () => getPosts())
}
// SomeComponent.jsx
import { fetchPost } from 'usePost';
import { fetchPosts } from 'usePosts';
function SomeComponent() {
const queries = useQueries([
{
queryKey: 'posts',
queryFn: fetchPosts
},
{
queryKey: ['post', id],
queryFn: fetchPost
}
]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With