-
In order to load data in a navigation-aware way, we obviously have great tooling with Unplugin Vue-Router and the Colada Loader. I have a use case though, where I am unsure as to what the best practice would be. I have data that is used across many pages and components and which needs to be loaded before any of them mount and regardless of route. This appears cumbersome to solve via Unplugin Vue Router, as the loaders would have to be added to many pages, and a tight coupling arises between pages and components which need the fetched data. So my idea was to simply fetch the data inside Here is my example which works: const QUERY_KEY = ['some-key']
router.beforeEach(async () => {
const queryCache = useQueryCache()
const hasCache = queryCache.getQueryData([QUERY_KEY])
if (!hasCache)
const queryEntry = queryCache.create([QUERY_KEY], {
query: () => graphQLClient.request(getMetadataDocument),
staleTime: Infinity,
key: [QUERY_KEY],
enabled: true,
refetchOnMount: false,
refetchOnReconnect: true,
refetchOnWindowFocus: false,
gcTime: false,
})
queryCache.caches.set([QUERY_KEY], queryEntry)
try {
const result = await graphQLClient.request(getMetadataDocument)
queryCache.setEntryState(queryEntry, {
data: result,
error: null,
status: 'success'
})
} catch (error: unknown) {
queryCache.setEntryState(queryEntry, {
data: undefined,
error: error,
status: 'error'
})
return {
name: '/some-redirect-route'
}
}
}
}) Looking at the source code of Pinia-Colada, it seems that some of the methods I am using are not meant to be called directly (i.e. Is there a better way to achieve this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Don't use queryCache.setQueryData(KEY, await graphQLClient.request(getMetadataDocument)) This is pretty much prefetching. It's not documented but it will |
Beta Was this translation helpful? Give feedback.
Don't use
create
, it's too low level. UsesetQueryData()
instead:This is pretty much prefetching. It's not documented but it will