AlbastruA
tRPC3y ago
10 replies
Albastru

eventemitter not having any listeners on websocket

Hi,

I have a app router project with TRPC but I created a websocket server alongside and a websocket client with the approuter and usecontext modified to work,

the problem is that first of all (i don't know if this is normal) it says there are two connections when i load a page
the next problem is that nothing gets emitted back from if i access a query diretly on my browser which is supposed to (as a test) send data back to the client.
the problem in the WS is that there are two weird responses which i don't understand

This is my code
import { EventEmitter } from "events";
import { initTRPC } from "@trpc/server";
import { observable } from "@trpc/server/observable";

const ee = new EventEmitter();

const t = initTRPC.create();

export const wsRouter = t.router({
   onAdd: t.procedure.subscription(() => {
      return observable((emit) => {
         const onAdd = (data: any) => {
            console.log("EMIT BABY!");
            emit.next(data);
         };
         ee.on("add", onAdd);
         return () => {
            ee.off("add", onAdd);
         };
      });
   }),
   add: t.procedure.query(async () => {
      const post = "hi";
      ee.emit("add", post);
      return post;
   }),
});


and this is what i have in the client

"use client";

import { useEffect } from "react";

import { client } from "~/trpc/ws";

const Page = () => {
   useEffect(() => {
      const subscription = client.ws.onAdd.subscribe(undefined, {
         onData(data) {
            console.log(data);
         },
      });
   }, []);

   return (
      <div>
         <h1>hi</h1>
      </div>
   );
};

export default Page;
image.png
Was this page helpful?