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

Update recipes.mdx: Using subscribe with selector #1388

Merged
merged 1 commit into from Oct 27, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 13 additions & 4 deletions docs/recipes/recipes.mdx
Expand Up @@ -131,21 +131,30 @@ subscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubs
```

```jsx
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand';
import { subscribeWithSelector, shallow } from 'zustand/middleware'
const useStore = create(subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })))

// Getting non-reactive fresh state
const paw = useStore.getState().paw
// Listening to all changes, fires on every change
const unsub1 = useStore.subscribe(console.log)
// Listening to selected changes, in this case when "paw" changes
const unsub2 = useStore.subscribe(console.log, state => state.paw)
const unsub2 = useStore.subscribe((state) => state.paw, console.log)
// Subscribe also supports an optional equality function
const unsub3 = useStore.subscribe(console.log, state => [state.paw, state.fur], shallow)
const unsub3 = useStore.subscribe(
(state) => [state.paw, state.fur],
console.log,
{ equalityFn: shallow }
)
// Subscribe also exposes the previous value
const unsub4 = useStore.subscribe((paw, previousPaw) => console.log(paw, previousPaw), state => state.paw)
const unsub4 = useStore.subscribe(
(state) => state.paw,
(paw, previousPaw) => console.log(paw, previousPaw)
)
// Updating state, will trigger listeners
useStore.setState({ paw: false })
useStore.setState({ snout: false })
// Unsubscribe listeners
unsub1()
unsub2()
Expand Down