Donald Biden
Donald Biden2d ago

A simple example of using SSE and subscriptions

Hello! Congrats on launching v11 🚀 I'm having a hard time to understand subscriptions](https://trpc.io/docs/server/subscriptions), specially the full stack example which is already a bit complex. Just wondering if there is a simple example somewhere without using React for example and just a basic subscription when a todo item is added for example. Also, is it just me or the onComplete, onData, etc options in a plain subscription got removed and is only available in useSubscription()? The types from v10 have it https://github.com/trpc/trpc/blob/3bc06d055d3b860d978e9c465bce56fdcf95b71f/packages/client/src/internals/TRPCUntypedClient.ts#L32 Thanks!
1 Reply
Sploopy
Sploopy22h ago
Which part are you confused on? The
.subscription
.subscription
trpc component or using it on the frontend?
export const SubscriptionEndpoint = publicProcedure
.subscription(async function* ({ _input, _ctx }) {
const redisSubscriber = new Redis(...)
const emitter = new EventEmitter()

try {
//Optional if you want to use redis
await redisSubscriber.subscribe("some_channel_name")
//Redis listening for messages
redisSubscriber.on("message", async () => {
//If you don't want to use Redis you can just use an event emitter alone
emitter.emit("update", subData)
})

//Async generator to keep the thread alive
for await (const output of on(emitter, "update")) {
//Yield the output to your frontend subscribers
yield output[0]
}
} catch (error) {
throw error
} finally {
redisSubscriber.unsubscribe("some_channel_name")
redisSubscriber.quit()
}
})
export const SubscriptionEndpoint = publicProcedure
.subscription(async function* ({ _input, _ctx }) {
const redisSubscriber = new Redis(...)
const emitter = new EventEmitter()

try {
//Optional if you want to use redis
await redisSubscriber.subscribe("some_channel_name")
//Redis listening for messages
redisSubscriber.on("message", async () => {
//If you don't want to use Redis you can just use an event emitter alone
emitter.emit("update", subData)
})

//Async generator to keep the thread alive
for await (const output of on(emitter, "update")) {
//Yield the output to your frontend subscribers
yield output[0]
}
} catch (error) {
throw error
} finally {
redisSubscriber.unsubscribe("some_channel_name")
redisSubscriber.quit()
}
})
export const SubscriptionComponent = () => {
trpc.SubscriptionRouter.SubscriptionEndpoint.useSubscription(
//Props here
{},
{
onData: (data) => {
//Do the thing with the data
},
})
}
export const SubscriptionComponent = () => {
trpc.SubscriptionRouter.SubscriptionEndpoint.useSubscription(
//Props here
{},
{
onData: (data) => {
//Do the thing with the data
},
})
}

Did you find this page helpful?