jperasmus / stale-while-revalidate-cache

Storage-agnostic and configurable stale-while-revalidate cache helper for any function, for any JavaScript environment.
MIT License
62 stars 5 forks source link

Invalidating a specific cache key? #23

Closed khromov closed 1 year ago

khromov commented 1 year ago

👋 I didn't see how to invalidate a particular cache key, for example if the underlying data has been updated and I want to be able to mark the current entry as stale (or delete it altogether).

jperasmus commented 1 year ago

Hi! This does not currently exist because the need for it has not come up before. I can add a method to delete a cache entry for a given cache key.

jperasmus commented 1 year ago

In v3.1.0 there is now a new delete() method that you can remove a cache entry for a given cache key.

const cacheKey = 'your-cache-key'

await swr.delete(cacheKey)
jraoult commented 1 year ago

Hi @jperasmus, I just found your library, and it seems perfect for my need. The only thing I seem to miss is invalidation (or forced revalidation). I think you implemented eviction here, but I'd like to hold onto the existing entry (even if stale) until the loader resolves. Am I getting it wrong?

jperasmus commented 1 year ago

Hi @jraoult Yes, you are correct, your use case sounds slightly different from the explicit eviction implemented in this issue.

In your case, we could look at something like (which would bypass the stale check):

const cacheKey = 'your-cache-key'
const cacheFunction = async () => 'your-value'

await swr.revalidate(cacheKey, cacheFunction)

I'm not sure what your exact use case is, but you could potentially achieve what you want by setting a short minTimeToStale with a longer maxTimeToLive and just invoking the swr(cacheKey, cacheFunction) whenever you want to revalidate. Would that work for your scenario?


EDIT: Or better yet, the main swr already allows overriding the config per invocation, so for your revalidate call you can do this:

const cacheKey = 'some-cache-key'
const yourFunction = async () => ({ something: 'useful' })
const configOverrides = {
  minTimeToStale: 0,
}

const result = await swr(cacheKey, yourFunction, configOverrides)

This will always revalidate your query.

jraoult commented 1 year ago

@jperasmus my use case is revalidating after mutation. I want to mark the value as stale and force revalidation, but if I try to access the key in the meantime I want it to return straight with the "stale" value. In this context, it seems like the minTimeToStale: 0 could do the job.