Chirp: the trpc call to get all posts, hits the database every re-render....

Is this expected behavior? Or is the way Theo wrote placing the get all posts just as a demonstration, and that a real app would do something to get the data and only requery when it needs? Such as using useEffect to get it once and store it until change is needed? In the index.tsx he has: api.posts.getAll.useQuery(); A similar query is in the feed component as well. I looked at planetscale's statistics page and sure enough it increments the count for the query to get all posts everytime the page rerenders, or even loses focus and regains it. There must be some caching going on since if you remove the line to .invalidate() after creating a new post, the get all query runs(and is counted on planetscale) but the new post doesn't appear in the feed. So I'm not quite sure what's happening...if prisma or trpc is determining that a cached result is fine, why does it still hit planetscale? Seems like alot of unecessary trips to the db.
4 Replies
whatplan
whatplan12mo ago
what your probably experiencing is react query's default of refetching all queries when the window is refocused (happens alot moving back and forth from dev server to editor), you can turn this off if you want but its not the default for no reason, someone who refocused may have not been using the page for a bit and the data might be stale in prod there will probably be multiple queries per second from having multiple users, planetscale is very robust I wouldnt be too worried unless you start to notice significant delays
whatplan
whatplan12mo ago
Window Focus Refetching | TanStack Query Docs
If a user leaves your application and returns and the query data is stale, TanStack Query automatically requests fresh data for you in the background. You can disable this globally or per-query using the refetchOnWindowFocus option: Disabling Globally
dconroy
dconroy12mo ago
Thanks, that would explain the refetch on window focus, but...for example I have a page that grabs data and presents it in a table, Theres a button on the page to open a modal to add a new record, but just the act of opening the modal(setting a state variable) causes the query to hit planetscale again. I have no doubt planetscale can handle it, even on the hobby plan, but overall, it just seems an inefficient and wastefully traffic heavy pattern...
whatplan
whatplan12mo ago
Hm Could you send the code in question?