Skip to content

Commit

Permalink
docs(atom-with-broadcast): update example code to work with TypeScript (
Browse files Browse the repository at this point in the history
#2716)

* docs(atom-with-broadcast): update example code to work with TypeScript

* chore: run prettier

* refactor(atom-with-broadcast): some types stuff

* refactor(atom-with-broadcast): put types in update
  • Loading branch information
hoangvu12 authored Aug 28, 2024
1 parent 7ca4b27 commit 1deb5e0
Showing 1 changed file with 12 additions and 5 deletions.
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

0 comments on commit 1deb5e0

Please sign in to comment.