Client Events
Note: If you are self-hosting pluv.io, we recommend using custom server events instead.
In pluv.io, you can define custom events with an input validation schema and a function, and have them be automatically type-safe without having to manage your own types.
Usage example
// ./frontend/pluv.ts
import { createClient, infer } from "@pluv/client";
import { createBundle } from "@pluv/react";
import { z } from "zod";
import type { ioServer } from "./backend/pluv-io";
const types = infer((i) => ({ io: i<typeof ioServer> }));
const io = createClient({ types });
// Create your custom events as procedures
const sendMessage = io.procedure
.input(z.object({ message: z.string() }))
.broadcast(({ message }) => ({
receiveMessage: { message },
}));
const doubleValue = io.procedure
.input(z.object({ value: z.number() }))
.broadcast(({ value }) => ({
receiveValue: { value: value * 2 },
}));
const wave = io.procedure
.broadcast(() => ({
receiveMessage: { message: "Hello world!" },
}));
// Then add the procedures to your router
const router = io.router({
sendMessage,
doubleValue,
wave,
});
// Lastly, add the router to your server, so that it can begin accepting
// custom events
const room = io.createRoom("my-custom-room", {
// ...,
router,
});
// If you are using @pluv/react, you would provide your router like so:
const { event, useBroadcast, useEvent } = createBundle(io, { router });
Sending events
import { io } from "frontend/pluv";
// This is your `PluvClient` from the previous code sample
const room = io.createRoom("...", { /* ... */ });
room.broadcast.sendMessage({ message: "Hello world!" });
room.broadcast.wave();
// If you are using @pluv/react
const broadcast = useBroadcast();
broadcast.sendMessage({ message: "hello world" });
broadcast.wave();
Receiving events
import { io } from "frontend/pluv";
// This is your `PluvClient` from the previous code sample
const room = client.createRoom("...", { /* ... */ });
room.event.receiveMessage(({ data }) => {
console.log(data.message);
});
room.event.receiveValue(({ data }) => {
console.log(data.value);
});
// If you are using @pluv/react
event.receiveMessage.useEvent(({ data }) => {
console.log(data.message);
});
event.receiveValue.useEvent(({ data }) => {
console.log(data.value);
});