Querying an API for a Details screen without a "details" endpoint
I'm using React Query with an API that has an endpoint where one can get a list of Foo's, but there is no endpoint to get the details of a specific Foo. I have two screens: a List screen and a Details screen. The List screen is set up to use the
useQuery
hook and call the API's list endpoint and populate the screen with an entry for each Foo. Each entry is clickable, and clicking will open the Details screen (passing in a unique Foo ID). However, that is where the data stops.
The Details screen has no way direct way to get the Details of a Foo, as there is no API endpoint for it. The best option I see is to use useQuery
again, and hope it hits the cache from the List screen (the list endpoint includes all the details), instead of sending out a new request. That still feels like bad data practice, though. A second option would be to use QueryClient.setQueryData
to set each individual cache for each Foo
, but I feel like that may also be frowned upon from a "best practices" perspective (setting the query data outside the normal way, fetching).
What should I do in this scenario?6 Replies
like-gold•2y ago
you can make a custom hook
useFoo(id)
that calls useQuery
internally that fetches the list, and you'd use select
to only select one piece of it. if you set a staleTime
, you won't see refetches, but you'll just pick an item from the list and your component is then subscribed to thatharsh-harlequinOP•2y ago
Thanks for the note. However, is there a performance hit when using
select
? The solution I engineered currently was to use QueryClient.setQueryData
and directly set the cache for new query keys related to each ID and then just calling those from the Details Screen with a mock query function.like-gold•2y ago
I wouldn't create a query without a queryFn
harsh-harlequinOP•2y ago
That's fair. I'll see if we can get backend to make an endpoint for indivudual details. Or maybe I'm just overthinking this. I just want to avoid too stale of data on the Details pages.
like-gold•2y ago
select is really good for that
harsh-harlequinOP•2y ago
Oh, I just realized another quirk. There are actually two list screens, each making a slight different query. Knowledge of the original query is lost when moving to the details screen, so we may not actually be able to know which query to call from there. I guess I could look into passing the query key down.