UNPKG

use-shared-sse

Version:

React hook for sharing Server-Sent Events across tabs using BroadcastChannel and Web Locks.

3 lines (2 loc) 1.01 kB
import{useRef as e,useEffect as n}from"react";function r({url:r,options:t={withCredentials:!0},events:a,channelName:c="sse-channel",lockName:o="sse-lock"}){const s=e(null),l=e(null);n((()=>(null===l.current&&(l.current=new BroadcastChannel(c)),l.current.onmessage=({data:{name:e,data:n}})=>{const r=a.find((n=>n.name===e));return r?.cb(n)},()=>{l.current?.close(),l.current=null})),[a]),n((()=>{const e=a.map((e=>{return{...e,cb:(n=l.current,r=e,e=>{n.postMessage({name:r.name,data:e.data}),r.cb(e.data)})};var n,r})),{promise:n,resolve:c}=function(){let e,n;const r=new Promise(((r,t)=>{e=r,n=t}));return{promise:r,resolve:e,reject:n}}(),u=new AbortController;return navigator.locks.request(o,{signal:u.signal},(()=>(s.current=new EventSource(r,t),e.forEach((e=>s.current?.addEventListener(e.name,e.cb))),n))),()=>{u.abort(),s.current&&(e.forEach((e=>s.current?.removeEventListener(e.name,e.cb))),s.current?.close(),s.current=null,c?.())}}),[r,t,a])}export{r as useSse}; //# sourceMappingURL=index.esm.js.map