Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Issue 1254 guides #1267

Merged
merged 3 commits into from
Sep 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions docs/guides/connect-to-state-with-url-hash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
title: Connect to state with URL hash
nav: 15
---

## State is connected with URL hash

If you want to connect state of a store to URL hash, you can create your own hash storage.

```ts
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,
}
)
)
```

## CodeSandbox Demo

https://codesandbox.io/s/silly-fire-gsjbc7?file=/src/App.tsx