Skip to content

Instantly share code, notes, and snippets.

@tomfa
Created August 15, 2024 12:49
Show Gist options
  • Save tomfa/aa299d187a918f798e052991cecbf1d7 to your computer and use it in GitHub Desktop.
Save tomfa/aa299d187a918f798e052991cecbf1d7 to your computer and use it in GitHub Desktop.
React Query: async fetch from cache or api
import { useQueryClient } from '@tanstack/react-query';
/*
* Demonstration of how to fetch data from API in a promise,
* but utilizing already cached data from React Query
* or (if not present) populate the cache after fetch.
*
* Motivation: reduce unnecessary data fetching.
*/
const Component = () => {
const queryClient = useQueryClient();
const [data, setData] = useState(null);
const onClick = async () => {
const cachedOrFreshData = await getPost(queryClient, 1);
setData(cachedOrFreshData);
}
return (
<button onClick={onClick}>Get post 1</button>
)
}
const getPost = async (qClient, id) => {
const queryKey = ['post', { id }];
const cachedData = qClient.getQueryData(queryKey);
if (cachedData) { return cachedData }
const response = await fetch('https://localhost:3000/api/posts/' + id);
const json = await response.json();
qClient.setQueryData(queryKey, json);
return json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment