T
TanStack2y ago
rare-sapphire

Only fetch once.

const { data, refetch, isFetched } = useQuery({
queryKey: ['todos'],
queryFn: () => (
fetch("http://localhost:3000/api/feed").then((res) => res.json())
),
enabled: false
})


const handleClick = () => {
if (!isFetched) {
refetch()
}
}
const { data, refetch, isFetched } = useQuery({
queryKey: ['todos'],
queryFn: () => (
fetch("http://localhost:3000/api/feed").then((res) => res.json())
),
enabled: false
})


const handleClick = () => {
if (!isFetched) {
refetch()
}
}
So I have a button that's across my entire Next.js site, I want to know if it's possible to make that when It's clicked the first time data will fetch but the second time it won't fetch and will use the info from the previous fetch. My above solution works but only on the current page. When I switch a page and click the button, it refetches.
3 Replies
fair-rose
fair-rose2y ago
By pages are they full page refreshes? If so you might want to look at: https://tanstack.com/query/latest/docs/framework/react/plugins/persistQueryClient If you're looking for a global state, Zustand is a good choice
fair-rose
fair-rose2y ago
staleTime: Infinity
fair-rose
fair-rose2y ago
Assuming it's not full page refreshes, yeah that's better

Did you find this page helpful?