Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created December 4, 2019 19:25
Show Gist options
  • Select an option

  • Save jtmthf/0a6066ec3e7a88a3cfc103b94685f9c0 to your computer and use it in GitHub Desktop.

Select an option

Save jtmthf/0a6066ec3e7a88a3cfc103b94685f9c0 to your computer and use it in GitHub Desktop.
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