Repository: tannerlinsley/react-query
Pull request #2360 (2021-06-09 11:53:46)

asyncStoragePersistor for React Native
**Implementation**

I looked at the createLocalStoragePersistor and just changed a few lines and necessary imports. Please feel free to suggest if there is anything I should change or improve.

**How to use**

```
import {asyncStoragePersistor} from './utility/createAsyncStoragePersistor';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      cacheTime: 1000 * 60 * 60 * 48, // 48 hours
      staleTime: 1000 * 60 * 60 * 24, // 24 hours
    },
  },
});

const storagePersistor = asyncStoragePersistor({
  asyncStorageKey: 'AsyncStorageReactQuery', // asyncStorageKey vs localStorageKey
  throttleTime: 1000,
});

persistQueryClient({
  queryClient,
  persistor: storagePersistor,
  maxAge: 1000 * 60 * 60 * 24, // 24 hours in milliseconds
});
```

**How to test**

Use some queries to get the data. Restart the React Native app. We should see the UIs with previously called queries immediately without needing to call the APIs.



vercel[bot]: This pull request is being automatically deployed with Vercel ([learn more](https://vercel.link/github-learn-more)).  
To see the status of your deployment, click below or on the icon next to each commit.

🔍 Inspect: [https://vercel.com/tannerlinsley/react-query/4TLxPbJNgshXRqp4VQwKRG2Hw3Vq](https://vercel.com/tannerlinsley/react-query/4TLxPbJNgshXRqp4VQwKRG2Hw3Vq)  
✅ Preview: *In Progress*


codesandbox[bot]: This pull request is automatically built and testable in [CodeSandbox](https://codesandbox.io).

  To see build info of the built libraries, click [here](https://ci.codesandbox.io/status/tannerlinsley/react-query/pr/2360/builds/138232) or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 6b96263c92b469ca001ab34fa71c976356162b29:

|Sandbox| Source |
|--|--|
|[tannerlinsley/react-query: basic](https://codesandbox.io/s/tannerlinsleyreact-query-basic-n9yci)| Configuration |
|[tannerlinsley/react-query: basic-typescript](https://codesandbox.io/s/tannerlinsleyreact-query-basic-typescript-10evd)| Configuration |

Aung-Myint-Thein: > looks good, but could you please streamline it with the other plugins, meaning:
> 
> * typescript
> * add to tsconfig.types.json
> * docs for the plugins
> * package.json
> * add it to the rollup config
> 
> basically, if you search for `createLocalStoragePersistor-experimental` everywhere, you'll see what you'll need to add :)

Added docs for plugins. Sorry, I am not a type script person and.. not very familiar with all the rollup config... :( 
TkDodo: no worries. I think I can check out the branch and add some commits I guess?
Aung-Myint-Thein: Please feel free to add more commits. I can verify that the code is working coz I am running the codes now and tested a few times by restarting the app and can confirm querycache data is there.
arnaudbzn: @TkDodo @Aung-Myint-Thein We are going to test this PR as well in the coming days. We'll keep you updated if we have any issues or comments.
TkDodo: can you please update your fork and branch with the latest release, as we've now made some changes to the webstorageplugin and I would like to avoid conflicts
TkDodo: build fails because:

> Cannot find module '@react-native-community/async-storage' or its corresponding type declarations.

How are we going to go about this please? I'd rather not add this as a `peerDependency`. Maybe it's better to change the interface to pass the actual `AsyncStorage` as a parameter to `asyncStoragePersistor` ? We've done something similar to the `WebStoragePersistor`...
TMaszko: @TkDodo What about async `setItem` ?
TkDodo: > @TkDodo What about async setItem ?

Yes, we'd need something as a parameter that has an async `getItem` and an async `setItem` method :)
TkDodo: > we'd need something as a parameter that has an async getItem and an async setItem method :)

tried that here: 06126123
TMaszko: > k, but we cannot just not throttle, can we? we can make it an `async` function to have it always return a Promise?

I think so :D
TMaszko: @TkDodo we could use smth like `p-throttle` https://github.com/sindresorhus/p-throttle wdyt?
TkDodo: > @TkDodo we could use smth like p-throttle https://github.com/sindresorhus/p-throttle wdyt?

what would be the drawback of just using the normal throttle that doesn't return anything?
TMaszko: Could be there race conditions? I mean one operation could be faster than the other one but order is not maintained on JS side 
TMaszko: Probably this package would even more fill our needs

Patch:
diff --git a/createAsyncStoragePersistor-experimental/package.json b/createAsyncStoragePersistor-experimental/package.json
new file mode 100644
index 000000000..6a1bf0b2c
--- /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/devtools/index.js b/devtools/index.js
index f65d19f8c..dc890413b 100644
--- a/devtools/index.js
+++ b/devtools/index.js
@@ -1,4 +1,4 @@
-if (process.env.NODE_ENV === 'production') {
+if (process.env.NODE_ENV !== 'development') {
   module.exports = {
     ReactQueryDevtools: function () {
       return null
diff --git a/docs/src/manifests/manifest.json b/docs/src/manifests/manifest.json
index 5d23536b7..e26cfc11d 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/comparison.md b/docs/src/pages/comparison.md
index be126934c..3b8a21fd5 100644
--- a/docs/src/pages/comparison.md
+++ b/docs/src/pages/comparison.md
@@ -47,7 +47,7 @@ Feature/Capability Key:
 | Prefetching APIs                                   | ✅                                       | 🔶                         | ✅                                    | ✅                                   |
 | Query Cancellation                                 | ✅                                       | 🛑                         | 🛑                                    | 🛑                                   |
 | Partial Query Matching<sup>3</sup>                 | ✅                                       | 🛑                         | 🛑                                    | ✅                                   |
-| Stale While Revalidate                             | ✅                                       | ✅                         | 🛑                                    | ✅                                   |
+| Stale While Revalidate                             | ✅                                       | ✅                         | ✅                                    | ✅                                   |
 | Stale Time Configuration                           | ✅                                       | 🛑                         | 🛑                                    | ✅                                   |
 | Pre-usage Query/Mutation Configuration<sup>4</sup> | ✅                                       | 🛑                         | 🛑                                    | ✅                                   |
 | Window Focus Refetching                            | ✅                                       | ✅                         | 🛑                                    | 🔶                                   |
@@ -71,7 +71,7 @@ Feature/Capability Key:
 
 > **<sup>5</sup> Automatic Refetch after Mutation** - For truly automatic refetching to happen after a mutation occurs, a schema is necessary (like the one graphQL provides) along with heuristics that help the library know how to identify individual entities and entities types in that schema.
 
-> **<sup>6</sup> Normalized Caching** - React Query and SWR do not currently support automatic-normalized caching which describes storing entities in a flat architecture to avoid some high-level data duplication.
+> **<sup>6</sup> Normalized Caching** - React Query, SWR and RTK-Query do not currently support automatic-normalized caching which describes storing entities in a flat architecture to avoid some high-level data duplication.
 
 <!-- -->
 
@@ -98,8 +98,8 @@ Feature/Capability Key:
 
 <!-- -->
 
-[rtk-query]: https://rtk-query-docs.netlify.app/
-[rtk-query-comparison]: https://rtk-query-docs.netlify.app/introduction/comparison
+[rtk-query]: https://redux-toolkit.js.org/rtk-query/overview
+[rtk-query-comparison]: https://redux-toolkit.js.org/rtk-query/comparison
 [bp-rtk]: https://badgen.net/bundlephobia/minzip/@reduxjs/toolkit?label=💾
 [bp-rtk-query]: https://badgen.net/bundlephobia/minzip/@rtk-incubator/rtk-query?label=💾
 [gh-rtk-query]: https://github.com/rtk-incubator/rtk-query
diff --git a/docs/src/pages/guides/query-functions.md b/docs/src/pages/guides/query-functions.md
index 4d1e60303..e31eb2548 100644
--- a/docs/src/pages/guides/query-functions.md
+++ b/docs/src/pages/guides/query-functions.md
@@ -8,12 +8,13 @@ A query function can be literally any function that **returns a promise**. The p
 All of the following are valid query function configurations:
 
 ```js
-useQuery(['todos', todoId], fetchTodoById)
+useQuery(['todos'], fetchAllTodos)
 useQuery(['todos', todoId], () => fetchTodoById(todoId))
 useQuery(['todos', todoId], async () => {
   const data = await fetchTodoById(todoId)
   return data
 })
+useQuery(['todos', todoId], ({ queryKey }) => fetchTodoById(queryKey[1]))
 ```
 
 ## Handling and Throwing Errors
diff --git a/docs/src/pages/plugins/createAsyncStoragePersistor.md b/docs/src/pages/plugins/createAsyncStoragePersistor.md
new file mode 100644
index 000000000..b7fc5b7f5
--- /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 d928e04dd..1236d0786 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/docs/src/users.js b/docs/src/users.js
index 052fd2cc5..55b6f14f7 100644
--- a/docs/src/users.js
+++ b/docs/src/users.js
@@ -19,4 +19,5 @@ export const users = [
   'EFI.com',
   'ReactBricks',
   'Nozzle.io',
+  'Uber',
 ]
diff --git a/package.json b/package.json
index bb919c3cc..bd851bd49 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 4e387b898..528bebbaf 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/core/queryObserver.ts b/src/core/queryObserver.ts
index cc1cd3e85..e1295cbd3 100644
--- a/src/core/queryObserver.ts
+++ b/src/core/queryObserver.ts
@@ -22,6 +22,7 @@ import type { QueryClient } from './queryClient'
 import { focusManager } from './focusManager'
 import { Subscribable } from './subscribable'
 import { getLogger } from './logger'
+import { isCancelledError } from './retryer'
 
 type QueryObserverListener<TData, TError> = (
   result: QueryObserverResult<TData, TError>
@@ -660,7 +661,7 @@ export class QueryObserver<
 
     if (action.type === 'success') {
       notifyOptions.onSuccess = true
-    } else if (action.type === 'error') {
+    } else if (action.type === 'error' && !isCancelledError(action.error)) {
       notifyOptions.onError = true
     }
 
diff --git a/src/createAsyncStoragePersistor-experimental/index.ts b/src/createAsyncStoragePersistor-experimental/index.ts
new file mode 100644
index 000000000..905fad209
--- /dev/null
+++ b/src/createAsyncStoragePersistor-experimental/index.ts
@@ -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)
+        }
+      }
+    })()
+}
diff --git a/src/devtools/devtools.tsx b/src/devtools/devtools.tsx
index 03729a5b2..4dd0f7649 100644
--- a/src/devtools/devtools.tsx
+++ b/src/devtools/devtools.tsx
@@ -133,6 +133,33 @@ export function ReactQueryDevtools({
     setIsResolvedOpen(isOpen)
   }, [isOpen, isResolvedOpen, setIsResolvedOpen])
 
+  // Toggle panel visibility before/after transition (depending on direction).
+  // Prevents focusing in a closed panel.
+  React.useEffect(() => {
+    const ref = panelRef.current
+    if (ref) {
+      function handlePanelTransitionStart() {
+        if (ref && isResolvedOpen) {
+          ref.style.visibility = 'visible'
+        }
+      }
+
+      function handlePanelTransitionEnd() {
+        if (ref && !isResolvedOpen) {
+          ref.style.visibility = 'hidden'
+        }
+      }
+
+      ref.addEventListener('transitionstart', handlePanelTransitionStart)
+      ref.addEventListener('transitionend', handlePanelTransitionEnd)
+
+      return () => {
+        ref.removeEventListener('transitionstart', handlePanelTransitionStart)
+        ref.removeEventListener('transitionend', handlePanelTransitionEnd)
+      }
+    }
+  }, [isResolvedOpen])
+
   React[isServer ? 'useEffect' : 'useLayoutEffect'](() => {
     if (isResolvedOpen) {
       const previousValue = rootRef.current?.parentElement.style.paddingBottom
@@ -186,6 +213,8 @@ export function ReactQueryDevtools({
             boxShadow: '0 0 20px rgba(0,0,0,.3)',
             borderTop: `1px solid ${theme.gray}`,
             transformOrigin: 'top',
+            // visibility will be toggled after transitions, but set initial state here
+            visibility: isOpen ? 'visible' : 'hidden',
             ...panelStyle,
             ...(isResizing
               ? {
@@ -378,9 +407,14 @@ export const ReactQueryDevtoolsPanel = React.forwardRef(
 
     React.useEffect(() => {
       if (isOpen) {
-        return queryCache.subscribe(() => {
+        const unsubscribe = queryCache.subscribe(() => {
           setUnsortedQueries(Object.values(queryCache.getAll()))
         })
+        // re-subscribing after the panel is closed and re-opened won't trigger the callback,
+        // So we'll manually populate our state
+        setUnsortedQueries(Object.values(queryCache.getAll()))
+
+        return unsubscribe
       }
       return undefined
     }, [isOpen, sort, sortFn, sortDesc, setUnsortedQueries, queryCache])
diff --git a/tsconfig.types.json b/tsconfig.types.json
index 3d0c8ff74..01f73034e 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/**/*"]


Test patch:
diff --git a/src/react/tests/useQuery.test.tsx b/src/react/tests/useQuery.test.tsx
index 7e94f0209..ae35708ca 100644
--- a/src/react/tests/useQuery.test.tsx
+++ b/src/react/tests/useQuery.test.tsx
@@ -473,6 +473,33 @@ describe('useQuery', () => {
     consoleMock.mockRestore()
   })
 
+  it('should not call onError when receiving a CancelledError', async () => {
+    const key = queryKey()
+    const onError = jest.fn()
+    const consoleMock = mockConsoleError()
+
+    function Page() {
+      useQuery<unknown>(
+        key,
+        async () => {
+          await sleep(10)
+          return 23
+        },
+        {
+          onError,
+        }
+      )
+      return null
+    }
+
+    renderWithClient(queryClient, <Page />)
+
+    await sleep(5)
+    await queryClient.cancelQueries(key)
+    expect(onError).not.toHaveBeenCalled()
+    consoleMock.mockRestore()
+  })
+
   it('should call onSettled after a query has been fetched', async () => {
     const key = queryKey()
     const states: UseQueryResult<string>[] = []