I got the prefetch to work previously by following the example on the official RTKQuery docs
in case the URL of the docs changes, here’s the example code:
type EndpointNames = keyof typeof api.endpoints
export function usePrefetchImmediately<T extends EndpointNames>(
endpoint: T,
arg: Parameters<(typeof api.endpoints)[T]["initiate"]>[0],
options: PrefetchOptions = {},
) {
const dispatch = useAppDispatch()
useEffect(() => {
dispatch(api.util.prefetch(endpoint, arg as any, options))
}, [])
}
// In a component
usePrefetchImmediately("getSomeData")
That was with useQuery
. However, I had to switch to useLazyQuery
as I needed to get the most up-to-date data from the API on each click of a button while still calling the API on first load of the page.
I can’t remember the exact StackOverflow post, but the example in the chosen / best answer was basically the following:
// getSomeData is usually shown as trigger on RTKQuery docs
const [getSomeData, { data, error, isLoading, isFetching, isUninitialized }] =
useLazyGetSomeDataQuery();
useEffect(() => {
if (isUninitialized) {
getSomeData();
}
}, []);
i.e. use a useEffect
Unfortunately, while doing so solved my problem, the data no longer gets prefetched after making this change.
I have tried searching a combination of the keywords RTKQuery
, useLazyQuery
and prefetch
, but can’t seem to find anything that solves this problem.