Last active
November 17, 2021 09:18
-
-
Save mwmwmw/65e143ef406062b8082ed4fe92645c23 to your computer and use it in GitHub Desktop.
A React Hook for using Pipedreams SSE endpoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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