Map과 Set을 객체로 감싼 상태에서, 해당 값을 갱신해야 할 때 setState
함수를 호출해서 갱신할 수 있다.
import create from 'zustand'
const useFooBar = create(() => ({ foo: new Map(), bar: new Set() }))
function doSomething() {
useFooBar.setState((prev) => ({
foo: new Map(prev.foo).set('newKey', 'newValue'),
bar: new Set(prev.bar).add('newKey'),
}))
}
hash는 #과 함꼐 URL에 붙는 요소
import create from 'zustand'
import { persist, StateStorage } 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)
},
setItem: (key, newValue): void => {
const searchParams = new URLSearchParams(location.hash.slice(1))
searchParams.set(key, JSON.stringify(newValue))
location.hash = searchParams.toString()
},
removeItem: (key): void => {
const searchParams = new URLSearchParams(location.hash.slice(1))
searchParams.delete(key)
location.hash = searchParams.toString()
},
}
export const useBoundStore = create(
persist(
(set, get) => ({
fishes: 0,
addAFish: () => set({ fishes: get().fishes + 1 }),
}),
{
name: 'food-storage', // unique name
getStorage: () => hashStorage,
}
)
)