Created
December 4, 2019 19:25
-
-
Save jtmthf/0a6066ec3e7a88a3cfc103b94685f9c0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import { useEffect, useState, useMemo } from 'react'; | |
| export interface UseEventSourceOptions<T = string> { | |
| withCredentials?: boolean; | |
| extractor?: (value: any) => T; | |
| } | |
| export function useEventSource<T = string>(url: string, { withCredentials, extractor = JSON.parse }: UseEventSourceOptions<T> = {}) { | |
| const [data, setData] = useState<T>(); | |
| const [readyState, setReadyState] = useState < 'connecting' | 'open' | 'closed' | 'error'>('connecting') | |
| useEffect(() => { | |
| const eventSource = new EventSource(url, { withCredentials }); | |
| setReadyState('connecting'); | |
| eventSource.onmessage = e => { | |
| setData(extractor(e.data)); | |
| } | |
| eventSource.onerror = e => { | |
| setReadyState('error'); | |
| } | |
| eventSource.onopen = e => { | |
| setReadyState('open'); | |
| } | |
| return () => { | |
| eventSource.close(); | |
| setReadyState('closed'); | |
| } | |
| }, [url, withCredentials]); | |
| return useMemo(() => ({ data, readyState }), [data, readyState]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment