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:
hellohy 2023-03-17 09:26:06 +08:00 committed by GitHub
parent 962f83e015
commit baf9b309c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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