-
Hi there, hopefully there a is a very simple answer to this question, however I couldn't find the answer I was looking for in the docs. BackgroundI have an app with two pages. The first is a "List" style page, where we want to display the results in a Table. We fetch the list of records and then give them a query key. For example: useQuery("records", () => fetchAllRecords()) The second is an "Edit/Create" style page where we display a single records details. We can create another query for this purpose. For example: useQuery(["record", { id }], () => fetchRecord(id)) ObjectiveIn this above scenario, we require two separate calls for data (1x All Records, 1x A Single Record). All works fantastically, however I would like to fetch All Records once and not require another request after navigating to the Edit Page. Conversely, when landing on the Edit Page for the first time, I'd like to get the record from cache and if it doesn't exist, fetch the Single Record and store it in cache. This can be acheived by checking the cache first and then optionally fetching the Record: const queryClient = useQueryClient();
const records = queryClient.getQueryData('records')
const record = records?.find(record => record.id === id)
const query = useQuery(["record", { id }], () => fetchRecord(id), { enabled: !!record }) Is there an easier way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Perhaps this is what I'm looking for? https://react-query.tanstack.com/guides/initial-query-data#initial-data-from-cache |
Beta Was this translation helpful? Give feedback.
-
yes, that’s exactly what you want. You’d likely need a small staleTime to avoid an instant background refetch. I’venust recently written about this: https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query |
Beta Was this translation helpful? Give feedback.
yes, that’s exactly what you want. You’d likely need a small staleTime to avoid an instant background refetch. I’venust recently written about this: https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query