Barebones React SSE Hook

For those of you using React. Here is a React hook that will make short work of implementing SSE in your application.

https://gist.github.com/mwmwmw/65e143ef406062b8082ed4fe92645c23

import { useCallback, useEffect, useState } from 'react';

export default function usePipeDreamSSE(
	endpointId,
	channel,
	callback = () => {},
) {
	const [eventSource, setEventSource] = useState();
	const [messages, setMessages] = useState([]);

	const send = useCallback(
		(message = '') =>
			fetch(`https://${endpointId}.m.pipedream.net/`, {
				method: 'post',
				body: JSON.stringify({ channel, message }),
			}).then((res) => res.json()),
		[endpointId, channel],
	);

	useEffect(() => {
		const src = new EventSource(
			`https://sdk.m.pipedream.net/pipelines/${endpointId}/sse`,
		);
		setEventSource(src);
	}, [endpointId]);

	useEffect(() => {
		if (eventSource) {
			
			setMessages([]);
			
			function handleEvent(e) {
				setMessages((prev) => {
					prev.push(e);
					return prev;
				});
				callback(JSON.parse(e.data));
			}

			eventSource.addEventListener(channel, handleEvent);

			return () => {
				eventSource.removeEventListener(channel, handleEvent);
			};
		}
	}, [eventSource, channel, callback]);

	return {
		send,
		messages,
	};
}

For the workflow, I use the simplest possible output.

const { channel } = event.body;

$send.sse({
  channel: channel,
  payload: event.body
});

It’s untested, could probably use more features, but will definitely get you up and running. Feel free to drop a comment here, the gist, or on Twitter if you have a question or suggestion.

1 Like