Skip to content

Instantly share code, notes, and snippets.

@luillyfe
Created November 30, 2023 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luillyfe/9caec1828bf62313eb02be4a5032e15c to your computer and use it in GitHub Desktop.
Save luillyfe/9caec1828bf62313eb02be4a5032e15c to your computer and use it in GitHub Desktop.
React router loader being cached
export function todosLoader(queryClient: QueryClient) {
return async function (): Promise<{ todos: Task[] }> {
const { queryKey, queryFn } = todosQuery();
// It does the trick for returning any data we have in the cache, even if it's stale.
// If the query does not exist, queryClient.fetchQuery will be called and its results returned.
const todos = (await queryClient.ensureQueryData({
queryKey,
queryFn,
})) as Task[];
return { todos };
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment