diff --git a/createAsyncStoragePersistor-experimental/package.json b/createAsyncStoragePersistor-experimental/package.json new file mode 100644 index 0000000000..6a1bf0b2cb --- /dev/null +++ b/createAsyncStoragePersistor-experimental/package.json @@ -0,0 +1,6 @@ +{ + "internal": true, + "main": "../lib/createAsyncStoragePersistor-experimental/index.js", + "module": "../es/createAsyncStoragePersistor-experimental/index.js", + "types": "../types/createAsyncStoragePersistor-experimental/index.d.ts" +} diff --git a/docs/src/manifests/manifest.json b/docs/src/manifests/manifest.json index 5d23536b78..e26cfc11db 100644 --- a/docs/src/manifests/manifest.json +++ b/docs/src/manifests/manifest.json @@ -312,6 +312,11 @@ "path": "/plugins/createWebStoragePersistor", "editUrl": "/plugins/createWebStoragePersistor.md" }, + { + "title": "createAsyncStoragePersistor (Experimental)", + "path": "/plugins/createAsyncStoragePersistor", + "editUrl": "/plugins/createAsyncStoragePersistor.md" + }, { "title": "broadcastQueryClient (Experimental)", "path": "/plugins/broadcastQueryClient", diff --git a/docs/src/pages/plugins/createAsyncStoragePersistor.md b/docs/src/pages/plugins/createAsyncStoragePersistor.md new file mode 100644 index 0000000000..b7fc5b7f59 --- /dev/null +++ b/docs/src/pages/plugins/createAsyncStoragePersistor.md @@ -0,0 +1,69 @@ +--- +id: createAsyncStoragePersistor +title: createAsyncStoragePersistor for React Native (Experimental) +--- + +> VERY IMPORTANT: This utility is currently in an experimental stage. This means that breaking changes will happen in minor AND patch releases. Use at your own risk. If you choose to rely on this in production in an experimental stage, please lock your version to a patch-level version to avoid unexpected breakages. + +## Installation + +This utility comes packaged with `react-query` and is available under the `react-query/createAsyncStoragePersistor-experimental` import. + +## Usage + +- Import the `createAsyncStoragePersistor` function +- Create a new asyncStoragePersistor +- Pass it to the [`persistQueryClient`](../persistQueryClient) function + +```ts +import { persistQueryClient } from 'react-query/persistQueryClient-experimental' +import { createAsyncStoragePersistor } from 'react-query/createAsyncStoragePersistor-experimental' + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + cacheTime: 1000 * 60 * 60 * 24, // 24 hours + }, + }, +}) + +const asyncStoragePersistor = createAsyncStoragePersistor() + +persistQueryClient({ + queryClient, + persistor: asyncStoragePersistor, +}) +``` + +## API + +### `createAsyncStoragePersistor` + +Call this function (with an optional options object) to create a asyncStoragePersistor that you can use later with `persisteQueryClient`. + +```js +createAsyncStoragePersistor(options?: CreateAsyncStoragePersistorOptions) +``` + +### `Options` + +An optional object of options: + +```js +interface CreateAsyncStoragePersistorOptions { + /** The key to use when storing the cache to localstorage */ + asyncStorageKey?: string + /** To avoid localstorage spamming, + * pass a time in ms to throttle saving the cache to disk */ + throttleTime?: number +} +``` + +The default options are: + +```js +{ + asyncStorageKey = `REACT_QUERY_OFFLINE_CACHE`, + throttleTime = 1000, +} +``` diff --git a/docs/src/pages/plugins/persistQueryClient.md b/docs/src/pages/plugins/persistQueryClient.md index d928e04dd3..1236d07867 100644 --- a/docs/src/pages/plugins/persistQueryClient.md +++ b/docs/src/pages/plugins/persistQueryClient.md @@ -10,6 +10,7 @@ title: persistQueryClient (Experimental) ## Officially Supported Persistors - [createWebStoragePersistor (Experimental)](/plugins/createWebStoragePersistor) +- [createAsyncStoragePersistor (Experimental)](/plugins/createAsyncStoragePersistor) ## Installation diff --git a/package.json b/package.json index bb919c3ccd..bd851bd495 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "devtools", "persistQueryClient-experimental", "createWebStoragePersistor-experimental", + "createAsyncStoragePersistor-experimental", "broadcastQueryClient-experimental", "lib", "react", diff --git a/rollup.config.js b/rollup.config.js index 4e387b8988..528bebbaf5 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -30,6 +30,11 @@ const inputSrcs = [ 'ReactQueryCreateWebStoragePersistorExperimental', 'createWebStoragePersistor-experimental', ], + [ + 'src/createAsyncStoragePersistor-experimental/index.ts', + 'ReactQueryCreateAsyncStoragePersistorExperimental', + 'createAsyncStoragePersistor-experimental', + ], [ 'src/broadcastQueryClient-experimental/index.ts', 'ReactQueryBroadcastQueryClientExperimental', diff --git a/src/createAsyncStoragePersistor-experimental/index.ts b/src/createAsyncStoragePersistor-experimental/index.ts new file mode 100644 index 0000000000..905fad2099 --- /dev/null +++ b/src/createAsyncStoragePersistor-experimental/index.ts @@ -0,0 +1,78 @@ +interface AsyncStorage { + getItem: (key: string) => Promise + setItem: (key: string, value: string) => Promise + removeItem: (key: string) => Promise +} + +interface CreateAsyncStoragePersistorOptions { + /** The storage client used for setting an retrieving items from cache */ + storage: AsyncStorage + /** The key to use when storing the cache */ + key?: string + /** To avoid spamming, + * pass a time in ms to throttle saving the cache to disk */ + throttleTime?: number +} + +export const asyncStoragePersistor = ({ + storage, + key = `REACT_QUERY_OFFLINE_CACHE`, + throttleTime = 1000, +}: CreateAsyncStoragePersistorOptions) => { + return { + persistClient: asyncThrottle( + persistedClient => storage.setItem(key, JSON.stringify(persistedClient)), + { interval: throttleTime } + ), + restoreClient: async () => { + const cacheString = await storage.getItem(key) + + if (!cacheString) { + return + } + + return JSON.parse(cacheString) + }, + removeClient: () => storage.removeItem(key), + } +} + +function asyncThrottle( + func: (...args: ReadonlyArray) => Promise, + { interval = 1000, limit = 1 }: { interval?: number; limit?: number } = {} +) { + if (typeof func !== 'function') throw new Error('argument is not function.') + const running = { current: false } + let lastTime = 0 + let timeout: number + const queue: Array = [] + return (...args: any) => + (async () => { + if (running.current) { + lastTime = Date.now() + if (queue.length > limit) { + queue.shift() + } + + queue.push(args) + clearTimeout(timeout) + } + if (Date.now() - lastTime > interval) { + running.current = true + await func(...args) + lastTime = Date.now() + running.current = false + } else { + if (queue.length > 0) { + const lastArgs = queue[queue.length - 1]! + timeout = setTimeout(async () => { + if (!running.current) { + running.current = true + await func(...lastArgs) + running.current = false + } + }, interval) + } + } + })() +} diff --git a/tsconfig.types.json b/tsconfig.types.json index 3d0c8ff748..01f73034e6 100644 --- a/tsconfig.types.json +++ b/tsconfig.types.json @@ -15,6 +15,7 @@ "./src/devtools/index.ts", "./src/persistQueryClient-experimental/index.ts", "./src/createWebStoragePersistor-experimental/index.ts", + "./src/createAsyncStoragePersistor-experimental/index.ts", "./src/broadcastQueryClient-experimental/index.ts" ], "exclude": ["./src/**/*"]