Last active
September 7, 2023 20:36
-
-
Save iRoachie/9df895d2a63d1789057c4f9cf1b7b833 to your computer and use it in GitHub Desktop.
Broadcast Channels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { z } from 'zod'; | |
import { Voter } from '@scc-voting/db/schemas/voter'; | |
export const QRCodePrompted = z.object({ | |
action: z.literal('QRCodePrompted'), | |
voter: Voter, | |
}); | |
export const QRCodeDismissed = z.object({ | |
action: z.literal('QRCodeDismissed'), | |
}); | |
export type QRCodePrompted = z.infer<typeof QRCodePrompted>; | |
export type QRCodeDismissed = z.infer<typeof QRCodeDismissed>; | |
export const connect = () => new BroadcastChannel('qr-events'); | |
export const sendQRCodePrompted = (channel: BroadcastChannel, voter: Voter) => { | |
channel.postMessage({ | |
action: 'QRCodePrompted', | |
voter, | |
}); | |
}; | |
export const sendQRCodeDismissed = (channel: BroadcastChannel) => { | |
channel.postMessage({ | |
action: 'QRCodeDismissed', | |
}); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Kiosk = () => { | |
const [voter, setVoter] = useState<Voter | null>(null); | |
useEffect(() => { | |
const channel = connect(); | |
channel.onmessage = (event) => { | |
const qrCodePrompted = QRCodePrompted.safeParse(event.data); | |
const qrCodeDismissed = QRCodeDismissed.safeParse(event.data); | |
if (qrCodePrompted.success) { | |
setVoter(qrCodePrompted.data.voter); | |
} | |
if (qrCodeDismissed.success) { | |
setVoter(null); | |
} | |
}; | |
return () => { | |
channel.close(); | |
}; | |
}, []); | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment