Reputation: 111
New to React-query, and I can't find any example of usage other than with rickandmorty api. The problem I'm having is that rickandmorty has episode/character id contained in the endpoint address, so you can pass that id, get data from the query cache and display it in another page. My api endpoint doesn't have an id contained. It looks like this: https://api.jsonbin.io/b/6231abada703bb67492d2b8f.
const { data, isLoading, isError } = useQuery(
'directories',
fetchDirectories,
);
After fetching, data is displayed in a list view. Clicking on each list item should take you to the details page for each item. I don't understand how to reference a particular item when calling useQuery in the details page. How to find a specific item in that cache?
Click navigates you to the url that has a business id as part of the url. How to access that business in the details page?
onClick={() => navigate(`business/${object.id}`)}
Upvotes: 2
Views: 4333
Reputation: 559
The main problem here is that your backend is missing a detailed view. So you would have to use the list query on your details page, I would advise against this in a real world scenario. On your detailed view component you can consume the hook using the same id and it should get it from the cache (it will trigger a refetch though unless you configure the staleTime
to something different than 0)
assuming you did:
// ListComponent.jsx
const { data, isLoading, isError } = useQuery(
'directories',
fetchDirectories,
{staleTime: 5000}
);
You should be able to do
// DetailedView.jsx
const { id } = useParams();
const { data, isLoading, isError } = useQuery(
'directories',
fetchDirectories,
staleTime: 5000
);
const myItem = data.find(item => item.id === id);
or you can get it straight from the cache like you mentioned, but If the cache is empty and react-query doesn't know the fetching function you will get nothing back from the cache
const data = queryClient.getQueryData('directories')
In an idea case what you want to do is fetch the list view, and maybe use setQueryData to get data to the individual queries like useQuery('directory', 1)
so they have data before hitting the detailed endpoint which doesn't exist for your backend as far as I know. You can accomplish what you want by using setQueryData
and getQueryData
as a work around for your lack of detailed endpoint, but more often than not you will want to work with useQuery
and not handle the cache like this.
Upvotes: 2