T
TanStack•3y ago
like-gold

Double fetching with React Router

I am using React Router v6 with a loader function. The loader is being called before the page loads, so initially, it runs and then displays the component/route. However, when I try to access query data using a hook, it makes a new request. Currently, it makes a request in the loader and then again when the component mounts. If I use getQueryData, I get the data received in the loader. postQuery() contains only the queryKey and Fn. How can I prevent double fetching for already fetched queries from loaders? I'm not sure if it makes sense to make double requests. P.S. I don't want to disable refetching everywhere, only in cases where the second call is redundant.
export const loader = async (queryClient: QueryClient) => {
let post: Post | undefined

try {
post = queryClient.getQueryData(postQuery(1).queryKey)

if (!post) {
post = await queryClient.fetchQuery(postQuery(1))
}
} catch (error) {
queryClient.resetQueries(postQuery(slug).queryKey)
throw new Response("Not Found", { status: 404 })
}

return post
}

export const PostView = () => {
const { data: post } = useQuery<PostData>(postQuery(1)) // fetching post again

const loaderPostData = queryClient.getQueryData(postQuery(1).queryKey) // returns fetched post in loader

return (
...
)
}
export const loader = async (queryClient: QueryClient) => {
let post: Post | undefined

try {
post = queryClient.getQueryData(postQuery(1).queryKey)

if (!post) {
post = await queryClient.fetchQuery(postQuery(1))
}
} catch (error) {
queryClient.resetQueries(postQuery(slug).queryKey)
throw new Response("Not Found", { status: 404 })
}

return post
}

export const PostView = () => {
const { data: post } = useQuery<PostData>(postQuery(1)) // fetching post again

const loaderPostData = queryClient.getQueryData(postQuery(1).queryKey) // returns fetched post in loader

return (
...
)
}
4 Replies
genetic-orange
genetic-orange•3y ago
First of all: you could use ensureQueryData The post is probably fetched again because of aggressive defaults I definitely recommend you read tkdodos blog. He has articles about using loader functions with react query, sane defaults and more 🙂 tkdodo.eu
like-gold
like-goldOP•3y ago
Then I am loosing all the features of useQuery hook. (if you are talking about using inside component, not loader) So my code looks the same as in the blog https://tkdodo.eu/blog/react-query-meets-react-router#querifying-the-example
extended-salmon
extended-salmon•3y ago
what's your staleTime ?
like-gold
like-goldOP•3y ago
I haven’t specified that. Made it 1 min and now it is not refetching. Solved it. Thank you!

Did you find this page helpful?