Custom Events
Define custom events on your backend PluvServer
or frontend PluvClient
. Then send and receive custom websocket events in a type-safe way with @pluv/react
.
Define custom events
To get started, define custom events in either your PluvServer or your PluvClient.
We'll create a sendMessage
and wave
events on our PluvClient
for this example:
// frontend/io
import { createClient } from "@pluv/client";
import { z } from "zod";
const io = createClient({ /* ... */ });
const sendMessage = io
.input(z.object({ message: z.string() }))
.broadcast(({ message }) => ({
receiveMessage: { message }
}));
const wave = io.broadcast(() => ({ receiveWave: {} }));
const router = io.router({ sendMessage, wave });
Then include the router
we created above into createBundle to connect the events to your frontend bundle.
import { createBundle } from "@pluv/react";
import { io, router } from "./frontend/io";
const {
event,
useBroadcast
} = createBundle(io, { router });
Use custom events
Assuming you've already setup your React bundle and providers, use can then use useBroadcast and event to broadcast and listen to the custom events defined from your router.
import { useCallback } from "react";
// These are exported from `createBundle`
import { event, useBroadcast } from "./frontend/io";
// Listen to events emitted from the `PluvIO` backend
event.receiveMessage.useEvent(({ data }) => {
console.log(data.message);
});
event.receiveValue.useEvent(({ data }) => {
console.log(data.value);
});
const broadcast = useBroadcast();
// Broadcast events to all participants
const sendMessage = useCallback((message: string): void => {
broadcast.sendMessage({ message });
}, [broadcast]);
const doubleValue = useCallback((value: number): void => {
broadcast.doubleValue({ value });
}, [broadcast]);