T
TanStack2y ago
fascinating-indigo

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
deep-jade
deep-jade2y 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
conscious-sapphire
conscious-sapphire2y ago
staleTime: Infinity
deep-jade
deep-jade2y ago
Assuming it's not full page refreshes, yeah that's better

Did you find this page helpful?