T
TanStack4y ago
rare-sapphire

Prefetch a query, then skip fetching when using the query

In order to avoid loading states I'm prefetching a query before navigating to a new screen. On that screen I'm using the query. If add a log to the queryFn I see it's being called when prefetched (as expected) and then again in the component calling useQuery (not as intended). I'm new to this library, is there a way I can set a cache setting or something so that I can avoid the second call when navigating but still get the benefits of useQuery for refetching afterwards? Component that does the prefetching:
import { queryKey, queryFn } from './MyScreen

export default function Prefetcher() {
const queryClient = useQueryClient();

return (
<Button
onPress={async () => {
await queryClient.prefetchQuery(queryKey, queryFn)
navigateToMyScreen()
}}
>
Prefetch, then navigate
</Button>
)
}
import { queryKey, queryFn } from './MyScreen

export default function Prefetcher() {
const queryClient = useQueryClient();

return (
<Button
onPress={async () => {
await queryClient.prefetchQuery(queryKey, queryFn)
navigateToMyScreen()
}}
>
Prefetch, then navigate
</Button>
)
}
Screen using the query
export const queryKey = ['my-screen']

export async function queryFn() {
// ...
}

export default function MyScreen() {
// 👇🏻 I want to skip this fetching immediately after I have just prefetched
const { data } = useQuery({ queryKey, queryFn })

// Use the data...
}
export const queryKey = ['my-screen']

export async function queryFn() {
// ...
}

export default function MyScreen() {
// 👇🏻 I want to skip this fetching immediately after I have just prefetched
const { data } = useQuery({ queryKey, queryFn })

// Use the data...
}
2 Replies
rare-sapphire
rare-sapphireOP4y ago
Here's a minimal reproduction. If you press the "Prefetch, then navigate" button you'll see two console logs "Calling queryFn". The first is during the prefetch and the second is once the MyScreen component with the useQuery call is mounted It turns out refetchOnMount: false is what I needed. I had tried that and it turns out my issue something else causing a rerender.
eastern-cyan
eastern-cyan4y ago
Hi I think your query uses the default staleTime (0). As such the data are considered stale right after the prefetch. Hence the query gets re fetched when another observer enters the game. Also the prefetchQuery function should be called with an object as parameter not 2 params

Did you find this page helpful?