@@ -9,17 +9,19 @@ type EventSourceOptions = {
9
9
* Subscribe to an event source and return the latest event.
10
10
* @param url The URL of the event source to connect to
11
11
* @param options The options to pass to the EventSource constructor
12
+ * @property withCredentials If true, send CORS headers
12
13
* @returns The last event received from the server
13
14
*/
14
15
export function useEventSource (
15
16
url : string | URL ,
16
- { event = "message" , init } : EventSourceOptions = { }
17
+ { event = "message" , init = { } } : EventSourceOptions = { }
17
18
) {
18
19
const [ data , setData ] = useState < string | null > ( null ) ;
20
+ const withCredentials = init . withCredentials ;
19
21
20
22
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 ) ;
23
25
24
26
// rest data if dependencies change
25
27
setData ( null ) ;
@@ -32,7 +34,7 @@ export function useEventSource(
32
34
eventSource . removeEventListener ( event ?? "message" , handler ) ;
33
35
eventSource . close ( ) ;
34
36
} ;
35
- } , [ url , event , init ] ) ;
37
+ } , [ url , event , withCredentials ] ) ;
36
38
37
39
return data ;
38
40
}
0 commit comments