Skip to content

Commit

Permalink
feat: asyncStoragePersistor for React Native (TanStack#2360)
Browse files Browse the repository at this point in the history
  • Loading branch information
Aung-Myint-Thein authored Jun 28, 2021
1 parent ddbd755 commit 7a628d6
Show file tree
Hide file tree
Showing 8 changed files with 166 additions and 0 deletions.
6 changes: 6 additions & 0 deletions createAsyncStoragePersistor-experimental/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
5 changes: 5 additions & 0 deletions docs/src/manifests/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
69 changes: 69 additions & 0 deletions docs/src/pages/plugins/createAsyncStoragePersistor.md
Original file line number Diff line number Diff line change
@@ -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,
}
```
1 change: 1 addition & 0 deletions docs/src/pages/plugins/persistQueryClient.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ title: persistQueryClient (Experimental)
## Officially Supported Persistors

- [createWebStoragePersistor (Experimental)](/plugins/createWebStoragePersistor)
- [createAsyncStoragePersistor (Experimental)](/plugins/createAsyncStoragePersistor)

## Installation

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"devtools",
"persistQueryClient-experimental",
"createWebStoragePersistor-experimental",
"createAsyncStoragePersistor-experimental",
"broadcastQueryClient-experimental",
"lib",
"react",
Expand Down
5 changes: 5 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ const inputSrcs = [
'ReactQueryCreateWebStoragePersistorExperimental',
'createWebStoragePersistor-experimental',
],
[
'src/createAsyncStoragePersistor-experimental/index.ts',
'ReactQueryCreateAsyncStoragePersistorExperimental',
'createAsyncStoragePersistor-experimental',
],
[
'src/broadcastQueryClient-experimental/index.ts',
'ReactQueryBroadcastQueryClientExperimental',
Expand Down
78 changes: 78 additions & 0 deletions src/createAsyncStoragePersistor-experimental/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
interface AsyncStorage {
getItem: (key: string) => Promise<string>
setItem: (key: string, value: string) => Promise<unknown>
removeItem: (key: string) => Promise<unknown>
}

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<T>(
func: (...args: ReadonlyArray<unknown>) => Promise<T>,
{ 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<any[]> = []
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)
}
}
})()
}
1 change: 1 addition & 0 deletions tsconfig.types.json
Original file line number Diff line number Diff line change
Expand Up @@ -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/**/*"]
Expand Down

0 comments on commit 7a628d6

Please sign in to comment.