-
I want to pass id to useQuery to fetch a post. Below is the relevant code from page. Below is the usePost hook. // hooks/usePosts.ts
export const usePost = (): UseQueryResult<unknown, unknown> => {
const router = useRouter();
const queryClient = useQueryClient();
return useQuery(["posts", router.query.id], fetchPost, {
staleTime: Infinity,
initialData: () => {
return queryClient
.getQueryData("posts")
?.find((d) => d.id === router.query.id);
},
enabled: typeof router.query.id === "undefined",
});
}; What I tried:
Below is code of parent component. // pages/posts/[id].tx
const Post = () => {
const { isLoading, isError, data } = usePost();
if (isLoading) {
return "loading...";
}
return (
<>
<h1>{data.title}</h1>
<p>{data.body}</p>
</>
);
};
export default Post;
export const getStaticProps: GetStaticProps = async ({ params }) => {
const id = params?.id;
const queryClient = new QueryClient();
await queryClient.prefetchQuery(["posts", id], fetchPost);
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
}; To clarify again, I need a way to use userQuery only when router has querystring. I have created a codesandbox to help in debugging. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The |
Beta Was this translation helpful? Give feedback.
The
enabled
option is still the way to go. Don't worry about the cache entry - the queryFn will not run when the query is disabled. It does show up in the devtools, but that's about it.