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(atom-with-broadcast): update example code to work with TypeScript #2716

Merged
merged 4 commits into from
Aug 28, 2024
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
17 changes: 12 additions & 5 deletions docs/recipes/atom-with-broadcast.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,43 +13,50 @@ By using the BroadcastChannel API, you can enable basic communication between br
According to the MDN documentation, receiving a message during initialization is not supported in the BroadcastChannel, but if you want to support that functionality, you may need to add extra option to atomWithBroadcast, such as local storage.

```tsx
import { atom } from 'jotai'
import { atom, SetStateAction } from 'jotai'

export function atomWithBroadcast<Value>(key: string, initialValue: Value) {
const baseAtom = atom(initialValue)
const listeners = new Set<(event: MessageEvent<any>) => void>()
const channel = new BroadcastChannel(key)

channel.onmessage = (event) => {
listeners.forEach((l) => l(event))
}

const broadcastAtom = atom<Value, { isEvent: boolean; value: Value }>(
const broadcastAtom = atom(
(get) => get(baseAtom),
(get, set, update) => {
(get, set, update: { isEvent: boolean; value: SetStateAction<Value> }) => {
set(baseAtom, update.value)

if (!update.isEvent) {
channel.postMessage(get(baseAtom))
}
},
)

broadcastAtom.onMount = (setAtom) => {
const listener = (event: MessageEvent<any>) => {
setAtom({ isEvent: true, value: event.data })
}

listeners.add(listener)

return () => {
listeners.delete(listener)
}
}
const returnedAtom = atom<Value, Value>(

const returnedAtom = atom(
(get) => get(broadcastAtom),
(get, set, update) => {
(_get, set, update: SetStateAction<Value>) => {
set(broadcastAtom, { isEvent: false, value: update })
},
)

return returnedAtom
}

const broadAtom = atomWithBroadcast('count', 0)

const ListOfThings = () => {
Expand Down