Skip to content

Commit

Permalink
doc: update documentation of persist (pmndrs#1512)
Browse files Browse the repository at this point in the history
* update documentation of persist to include how to handle Map and Set with the new persist API

* run prettier

* Update docs/integrations/persisting-store-data.md

Co-authored-by: Chris K <[email protected]>

* Update docs/integrations/persisting-store-data.md

Co-authored-by: Chris K <[email protected]>

* Update docs/integrations/persisting-store-data.md

Co-authored-by: Blazej Sewera <[email protected]>

* edit suggestions

* fix comment

Co-authored-by: Chris K <[email protected]>
Co-authored-by: Blazej Sewera <[email protected]>
  • Loading branch information
3 people authored Jan 10, 2023
1 parent 0b55a3d commit 725c2c0
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions docs/integrations/persisting-store-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -571,3 +571,39 @@ export const useBearStore = create<MyState>()(
)
)
```

### How do I use it with Map and Set?

With the previous persist API, you would use `serialize`/`deserialize`
to deal with `Map` and `Set` and convert them into
an Array so they could be parsed into proper JSON.

The new persist API has deprecated `serialize`/`deserialize`.

Now, you will need to use the `storage` prop.
Let's say your state uses `Map` to handle a list of `transactions`,
then you can convert the Map into an Array in the storage prop:

```ts
storage: {
getItem: (name) => {
const str = localStorage.getItem(name)
return {
state: {
...JSON.parse(str).state,
transactions: new Map(JSON.parse(str).state.transactions),
},
}
},
setItem: (name, newValue) => {
const str = JSON.stringify({
state: {
...newValue.state,
transactions: Array.from(newValue.state.transactions.entries()),
},
})
localStorage.setItem(name, str)
},
removeItem: (name) => localStorage.removeItem(name),
},
```

0 comments on commit 725c2c0

Please sign in to comment.