Run trpc query...on first render only!
I have been wasting hours and HOURS trying to figure out how to call a trpc query on the first render only.
I am querying data that populates a drop down select input. When an option is selected, my state updates and the component re-renders which calls the data again.
I don't want to call the data again.
1. I can't call it inside of useEffect because it breaks the rules of hooks.
2. I've also tried wrapping the query in a useCallback & returning the data to set inside of a useEffect but I just get a "prevDeps is undefined" error.
Another error that I've seen is "observer.getOptimisticResult is not a function" if I just use useCallback without useEffect. Weird stuff.
Does anyone have any suggestion on how to do this?
With a code example :/
7 Replies
Stack Overflow
How to fetch user details only once
I have several components that make use of user details.
Since user details don't change that often, I want to fetch them only once.
One way would be -
const twentyFourHoursInMs = 1000 * 60 * 60 * 24
look at tkdodos answer
you can give these options to a single query, or to your entire queryclient
trpc is basically just react query in the frontend
Thank you!!! @cje
tkdodo's the man!
he has a fantastic series on react query, highly-highly recommend
https://tkdodo.eu/blog/practical-react-query
Practical React Query
Let me share with you the experiences I have made lately with React Query. Fetching data in React has never been this delightful...
Do you guys use query keys? So far I haven't had a need to. I've been able to use useContext for invalidating & interacting with the cache
yeah that's a big plus with
trpc !
you don't need to manage the keys manually, which is kind of a pain in the ass, to be honest, and kind of easy to make stupid mistakes when managed by handuseContext | tRPC
useContext is a hook that gives you access to helpers that let you manage the cached data of the queries you execute via @trpc/react-query. These helpers are actually thin wrappers around @tanstack/react-query's queryClient methods. If you want more in-depth information about options and usage patterns for useContext helpers than what we provide...