Skip to content

Add change description info to cache.subscribe #630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
gaoxiaoliangz opened this issue Sep 2, 2020 · 4 comments
Closed

Add change description info to cache.subscribe #630

gaoxiaoliangz opened this issue Sep 2, 2020 · 4 comments

Comments

@gaoxiaoliangz
Copy link

gaoxiaoliangz commented Sep 2, 2020

import { cache } from 'swr'

const listener = (e) => {
  console.log(e) // undefined
  syncAllCacheToLocalStorage()
}

cache.subscribe(listener)

Currently nothing is passed to the listener function. I would like to impl some sort of cache sync in my app (sync between localStorage and swr cache). And I would like to know which cache key changed, so that I would not need to iterate through every key and update every cache to localStorage.

@ryaninvents
Copy link

@gaoxiaoliangz Just as a heads up, looks like #365 will implement this when merged.

@huozhi
Copy link
Member

huozhi commented Sep 21, 2020

@gaoxiaoliangz you can use the following code to access the iterative value pairs in the swr cache, then you can sync/serialize it to local storage as a workaround

const listener = () => {
  const cacheKvPairs = cache.keys().map(key => ([key, cache.get(key)]))
  syncToLocalStorage(cacheKvPairs)
}

but since the cache APIs are not documented officially, it means cache calls might have breaking changes in the future when you upgrade swr to higher version.

@gaoxiaoliangz
Copy link
Author

@gaoxiaoliangz you can use the following code to access the iterative value pairs in the swr cache, then you can sync/serialize it to local storage as a workaround

const listener = () => {
  const cacheKvPairs = cache.keys().map(key => ([key, cache.get(key)]))
  syncToLocalStorage(cacheKvPairs)
}

but since the cache APIs are not documented officially, it means cache calls might have breaking changes in the future when you upgrade swr to higher version.

This is actually what I impl now, but the problem is that there is too much data to sync, and each time new data arrives I have to check them all in order to sync them to local, this is really inefficient.

@huozhi
Copy link
Member

huozhi commented Jun 28, 2021

You could use custom cache to build out this feature now. Checkout cache#sync-cache-to-localstorage for details

@huozhi huozhi closed this as completed Jun 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants