Skip to content

Instantly share code, notes, and snippets.

@mwmwmw
Last active Nov 17, 2021
Embed
What would you like to do?
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