Skip to content

Instantly share code, notes, and snippets.

@iRoachie
Last active September 7, 2023 20:36
Show Gist options
  • Save iRoachie/9df895d2a63d1789057c4f9cf1b7b833 to your computer and use it in GitHub Desktop.
Save iRoachie/9df895d2a63d1789057c4f9cf1b7b833 to your computer and use it in GitHub Desktop.
Broadcast Channels
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',
});
};
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