From 7064c694839d4d21dd61cfa3195073562f0a49b0 Mon Sep 17 00:00:00 2001 From: hverlin Date: Thu, 10 Feb 2022 20:47:46 +0100 Subject: [PATCH] docs: Document compression use case for `createWebStoragePersister` (#3285) Add an example on how to `compress`/`decompress` data from local storage in case you need to cache large payloads. Context: https://github.com/tannerlinsley/react-query/pull/2864#issuecomment-1034604428 --- .../plugins/createWebStoragePersister.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/src/pages/plugins/createWebStoragePersister.md b/docs/src/pages/plugins/createWebStoragePersister.md index 58f9d93168..ced3302e20 100644 --- a/docs/src/pages/plugins/createWebStoragePersister.md +++ b/docs/src/pages/plugins/createWebStoragePersister.md @@ -72,3 +72,27 @@ The default options are: deserialize = JSON.parse, } ``` + +#### `serialize` and `deserialize` options +There is a limit to the amount of data which can be stored in `localStorage`. +If you need to store more data in `localStorage`, you can override the `serialize` and `deserialize` functions to compress and decrompress the data using a library like [lz-string](https://github.com/pieroxy/lz-string/). + +```js +import { QueryClient } from 'react-query'; +import { persistQueryClient } from 'react-query/persistQueryClient' +import { createWebStoragePersister } from 'react-query/createWebStoragePersister' + +import { compress, decompress } from 'lz-string'; + +const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } }); + +persistQueryClient({ + queryClient: connectionsQueryClient, + persistor: createWebStoragePersister({ + storage: window.localStorage, + serialize: data => compress(JSON.stringify(data)), + deserialize: data => JSON.parse(decompress(data)), + }), + maxAge: Infinity, +}); +```