mirror of
https://github.com/pmndrs/zustand.git
synced 2025-12-08 19:45:52 +00:00
fix(doc): update state-with-url-hash demo (#1687)
* fix(doc): update state-with-url-hash demo * fix(doc): url-hash demo better code
This commit is contained in:
parent
962f83e015
commit
baf9b309c1
@ -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))
|
||||
@ -37,7 +37,7 @@ export const useBoundStore = create(
|
||||
}),
|
||||
{
|
||||
name: 'food-storage', // unique name
|
||||
getStorage: () => hashStorage,
|
||||
storage: createJSONStorage(() => hashStorage),
|
||||
}
|
||||
)
|
||||
)
|
||||
@ -45,4 +45,4 @@ export const useBoundStore = create(
|
||||
|
||||
## 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
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user