Skip to content

Commit

Permalink
Support withCredentials in useEventSource()
Browse files Browse the repository at this point in the history
  • Loading branch information
kensnyder authored Sep 20, 2023
1 parent a2324ac commit ed63e48
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/react/use-event-source.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,19 @@ type EventSourceOptions = {
* Subscribe to an event source and return the latest event.
* @param url The URL of the event source to connect to
* @param options The options to pass to the EventSource constructor
* @property withCredentials If true, send CORS headers
* @returns The last event received from the server
*/
export function useEventSource(
url: string | URL,
{ event = "message", init }: EventSourceOptions = {}
{ event = "message", init = {} }: EventSourceOptions = {}

This comment has been minimized.

Copy link
@kensnyder

kensnyder Sep 20, 2023

Author

If you pass an object as init the hook will call close/open every render because the init object is a by-reference dependency of the useEffect. MDN currently only documents one possible option: withCredentials: boolean;.

In this PR I just handle withCredentials specially. An alternative would be to just remove init from the dependency array because changing it after creating the EventSource doesn't make sense. Another possible solution is to use JSON.stringify() outside the useEffect and JSON.parse() inside the useEffect.

) {
const [data, setData] = useState<string | null>(null);
const withCredentials = init.withCredentials;

useEffect(() => {
const eventSource = new EventSource(url, init);
eventSource.addEventListener(event ?? "message", handler);
const eventSource = new EventSource(url, { withCredentials });
eventSource.addEventListener("message", handler);

// rest data if dependencies change
setData(null);
Expand All @@ -32,7 +34,7 @@ export function useEventSource(
eventSource.removeEventListener(event ?? "message", handler);
eventSource.close();
};
}, [url, event, init]);
}, [url, event, withCredentials]);

return data;
}

0 comments on commit ed63e48

Please sign in to comment.