Why ensureQueryData instead of prefetchQuery?
This question is overlapping with #query , but posting it here since I am asking about the usage of react-query in react-router:
The react-router documentation and the react-router examples based on react-query all use code like this:
Wouldn't it be better to use
Quoting from the react-query docs (see https://tanstack.com/query/v4/docs/react/reference/QueryClient#queryclientfetchquery)
Whereas
I saw a difference for the following use case:
I have a list view, and a separate detail view. When data is modified in the detail view, the query key of the list view is invalidated and then navigates back to the list view.
With
When the list view is shown after data modification, it briefly shows the outdated data, fetches the updated data from the backend and then refreshes the list to show the latest state.
With
The react-router documentation and the react-router examples based on react-query all use code like this:
Wouldn't it be better to use
prefetchQuery instead of ensureQueryData here?Quoting from the react-query docs (see https://tanstack.com/query/v4/docs/react/reference/QueryClient#queryclientfetchquery)
If the query exists and the data is not invalidated or older than the given staleTime, then the data from the cache will be returned. Otherwise it will try to fetch the latest data.
Whereas
ensureQueryData does not check if the data is invalidated (see https://tanstack.com/query/v4/docs/react/reference/QueryClient#queryclientensurequerydata)ensureQueryData is an asynchronous function that can be used to get an existing query's cached data. If the query does not exist, queryClient.fetchQuery will be called and its results returned.
I saw a difference for the following use case:
I have a list view, and a separate detail view. When data is modified in the detail view, the query key of the list view is invalidated and then navigates back to the list view.
With
ensureQueryData:When the list view is shown after data modification, it briefly shows the outdated data, fetches the updated data from the backend and then refreshes the list to show the latest state.
With
prefetchQuery, the list view never shows the outdated item.QueryClient
The QueryClient can be used to interact with a cache:
The QueryClient can be used to interact with a cache: