Skip to content

Commit

Permalink
fix(doc): update state-with-url-hash demo (#1687)
Browse files Browse the repository at this point in the history
* fix(doc): update state-with-url-hash demo

* fix(doc): url-hash demo better code
  • Loading branch information
hi-otto authored Mar 17, 2023
1 parent 962f83e commit baf9b30
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions docs/guides/connect-to-state-with-url-hash.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ If you want to connect state of a store to URL hash, you can create your own has

```ts
import { create } from 'zustand'
import { persist, StateStorage } from 'zustand/middleware'
import { persist, StateStorage, createJSONStorage } from 'zustand/middleware'

const hashStorage: StateStorage = {
getItem: (key): string => {
const searchParams = new URLSearchParams(location.hash.slice(1))
const storedValue = searchParams.get(key)
return JSON.parse(storedValue)
const storedValue = searchParams.get(key) ?? ''
return storedValue
},
setItem: (key, newValue): void => {
const searchParams = new URLSearchParams(location.hash.slice(1))
Expand All @@ -37,12 +37,12 @@ export const useBoundStore = create(
}),
{
name: 'food-storage', // unique name
getStorage: () => hashStorage,
storage: createJSONStorage(() => hashStorage),
}
)
)
```

## CodeSandbox Demo

https://codesandbox.io/s/silly-fire-gsjbc7?file=/src/App.tsx
https://codesandbox.io/s/zustand-state-with-url-hash-demo-pn20n5?file=/src/store/index.ts

0 comments on commit baf9b30

Please sign in to comment.