Kong / swrv

Stale-while-revalidate data fetching for Vue

Home Page:https://docs-swrv.netlify.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Query batching and caching objects with multiple keys

aantn opened this issue · comments

My application needs to load a single type of REST resource from a backend. The resource can be loaded by ID or in batches - for example, all objects modified in the last 24 hours.

Is it possible to use swrv such that the same caching layer will be used regardless of how I load those resources? For example, when loading all resources modified in the past 24 hours, I would like to cache the results of that query with a key like /recent/xyz but each individual item returned should also be cached as /resource/<id>?

An example use case for this is a blogging platform where the most recent blog posts are loaded on the home page. When clicking on an individual blog post from the homepage, I would like to avoid reloading that blog post as all the data is already present in the cache.

Technically speaking, I would like to use an api like: explicitlyAddToCache(secondaryKey, someData).

you can mutate a cache by any key and populate it with whatever you want via mutate.
https://docs-swrv.netlify.app/features.html#prefetching

So there are a couple ways you could prime it. If you watch the data from the /recent/xyz endpoint, then you can read all the posts and mutate the cache, then on the pages the caches will have been primed (and then subsequently revalidated per the cache strategy).

something like this:

// Recent.vue
const { data } = useSWRV(`/recent/xyz`, (url) => fetch(url).then(res => res.json()));

watchEffect(() => {
  data.recent.forEach(post => {
    mutate(`/recent/${post.id}`, post)
  })
})

// Post.vue
const { data } = useSWRV(`/recent/${id}`, (url) => fetch(url).then(res => res.json()));