What's a nice code pattern to revalidatePath on each query?
I have a page that polls for data every 5 seconds. The query loads fine but doesn't show until I have manually revalidated the path (to clear the cache)
Is there a best practice for doing this reliably?
10 Replies
passive-yellow•10mo ago
Can you share more about your setup? How are you polling, is it via
refetchInterval
?
It's surprising to me that you'd have to manually revalidate the query key.absent-sapphireOP•10mo ago
Hey, thanks @ballingt - Yes, I'm using
reftechInterval
and the query runs perfectly. The issue is that NextJs cache's the data at the route level so you need to clear it manually using NextJs revalidatePath('/my-path')
.
I'd like to be able to do run my fetch function but also clear the data when it runs... it seems to end up in a loop at the moment.
Wait... I'm such an idiot.
I can just use a function to do both...
With a function to do both...
I'll try that!optimistic-gold•10mo ago
I'd be worried about the
queryFn
not being pure in your case, revalidatePath
is technically a side effect (no, you are not allowed to use useEffect
here)
Does NextJs have its own version of refetchInterval
?absent-sapphireOP•10mo ago
ah OK thanks @DogPawHat so it's not 'polling' as such...
I could live with it refetching when one of the function args changed, rather than on an interval. Would you handle that in a
useEffect
?
So:
objectId
and pupilId
are handled by select filters, how wuld you handle refetching when they change?optimistic-gold•10mo ago
objectId
and pupilId
need to be in the queryKey
queryKey
works like a dep array
There's another thing I'd like to mention, assuming your using App Router, there's quite a bit of overlap between query and the RSCs in App Router
These docs are quite useful i thinkoptimistic-gold•10mo ago
TanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.

optimistic-gold•10mo ago
https://nextjs.org/docs/app/building-your-application/caching and these might help too. Gotta be honest, I'm not too familiar with this part
Building Your Application: Caching | Next.js
An overview of caching mechanisms in Next.js.
optimistic-gold•10mo ago
I'd be curious to see your project if your allowed to share it, I can probably give some quick architectural advice.
absent-sapphireOP•10mo ago
objectId and pupilId need to be in the queryKey queryKey works like a dep arrayoh my lord, I didn't clock that, that's great news. I was trying to do this manually 🤦♂️ So as I change the filters it will act as separate queries? That's great news. @DogPawHat - I would love to share what I'm doing, the repo isn't public but I'd love a pair of eyes over it. I wouldn't expect your guidance for free though.
optimistic-gold•10mo ago
Fair enough. I'll send a discord friend request and see if we can work something out.