Skip to content

Instantly share code, notes, and snippets.

@mwmwmw
Last active November 17, 2021 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwmwmw/65e143ef406062b8082ed4fe92645c23 to your computer and use it in GitHub Desktop.
Save mwmwmw/65e143ef406062b8082ed4fe92645c23 to your computer and use it in GitHub Desktop.
A React Hook for using Pipedreams SSE endpoints
/**
This hook is for interacting with Pipedreams Server Signal Events.
Padd in the endpointId, channel to listen to, and a callback function for when an event arrives.
Passed out of the hook is a function for sending messages back to the server as well as a list of messages.
*/
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,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment