Skip to content

Commit ed63e48

Browse files
authored
Support withCredentials in useEventSource()
1 parent a2324ac commit ed63e48

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/react/use-event-source.tsx

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,19 @@ type EventSourceOptions = {
99
* Subscribe to an event source and return the latest event.
1010
* @param url The URL of the event source to connect to
1111
* @param options The options to pass to the EventSource constructor
12+
* @property withCredentials If true, send CORS headers
1213
* @returns The last event received from the server
1314
*/
1415
export function useEventSource(
1516
url: string | URL,
16-
{ event = "message", init }: EventSourceOptions = {}
17+
{ event = "message", init = {} }: EventSourceOptions = {}
1718
) {
1819
const [data, setData] = useState<string | null>(null);
20+
const withCredentials = init.withCredentials;
1921

2022
useEffect(() => {
21-
const eventSource = new EventSource(url, init);
22-
eventSource.addEventListener(event ?? "message", handler);
23+
const eventSource = new EventSource(url, { withCredentials });
24+
eventSource.addEventListener("message", handler);
2325

2426
// rest data if dependencies change
2527
setData(null);
@@ -32,7 +34,7 @@ export function useEventSource(
3234
eventSource.removeEventListener(event ?? "message", handler);
3335
eventSource.close();
3436
};
35-
}, [url, event, init]);
37+
}, [url, event, withCredentials]);
3638

3739
return data;
3840
}

0 commit comments

Comments
 (0)