Next.js Discord

Discord Forum

Is it impossible to initialize EventSource in a Class?

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
I'm trying to use EventSource to get SSE events from the backend server and also want to use Singleton pattern to use the EventSource instance anywhere in my code.
But I always get this error after a minute later when its connected to the SSE.
(the error is in the image below)
It always receives 1 or 2 events very well but then it shows an error.
Here is my code below!

SSE class
import { getSHA256 } from '@/shared/lib';
import { SSEProps } from '@/shared/types';

export class SSE {
  private static eventSource: EventSource;
  private static clientId: string;

  private static init({ onKeywordList }: SSEProps) {
    const clientId = getSHA256(String(new Date().getMilliseconds()));

    console.log('clientId: ', clientId);

    const eventSource = new EventSource(
      `${process.env.NEXT_PUBLIC_REST_API_URL}/api/v1/subscribe?clientId=${clientId}`
    );

    eventSource.onopen = () => {
      console.log('SSE connection is ready');
    };

    eventSource.onmessage = (e) => {
      console.log(e);
    };

    eventSource.onerror = (err) => {
      console.log(err);
      eventSource.close();
    };

    eventSource.addEventListener('signalKeywordList', (e) => onKeywordList?.(JSON.parse(e.data)));

    SSE.eventSource = eventSource;
    SSE.clientId = clientId;
  }

  static getInstance({ onKeywordList }: SSEProps) {
    if (!SSE.eventSource) {
      SSE.init({ onKeywordList });
    }

    return { eventSource: SSE.eventSource, clientId: SSE.clientId };
  }
}


An example of use
export default function TrendBar() {
  const [top10, setTop10] = useState<Top10[]>();
  ...

  useEffect(() => {
    const { eventSource, clientId } = SSE.getInstance({
      onKeywordList: (data) => {
        console.log(data);
        setTop10(data.top10WithDiff);
      },
    });

    return () => {
      eventSource?.close();
      (async () => await axiosDisconnectSSE(clientId))();
    };
  }, []);

  ...
}


Can you give me some advice to fix the problem?

0 Replies