@@ -8,6 +8,7 @@ import type {
88 Connection ,
99 ModelEvents ,
1010 ModelPayload ,
11+ Notification ,
1112} from "../types" ;
1213import { toArray } from "../util" ;
1314
@@ -163,6 +164,78 @@ export const useEcho = <
163164 } ;
164165} ;
165166
167+ export const useEchoNotification = <
168+ TPayload ,
169+ TDriver extends BroadcastDriver = BroadcastDriver ,
170+ > (
171+ channelName : string ,
172+ callback : ( payload : Notification < TPayload > ) => void = ( ) => { } ,
173+ event : string | string [ ] = [ ] ,
174+ dependencies : any [ ] = [ ] ,
175+ ) => {
176+ const result = useEcho < Notification < TPayload > , TDriver , "private" > (
177+ channelName ,
178+ [ ] ,
179+ callback ,
180+ dependencies ,
181+ "private" ,
182+ ) ;
183+
184+ const events = toArray ( event ) ;
185+ const listening = useRef ( false ) ;
186+ const initialized = useRef ( false ) ;
187+
188+ const cb = useCallback (
189+ ( notification : Notification < TPayload > ) => {
190+ if ( ! listening . current ) {
191+ return ;
192+ }
193+
194+ if ( events . length === 0 || events . includes ( notification . type ) ) {
195+ callback ( notification ) ;
196+ }
197+ } ,
198+ dependencies . concat ( events ) . concat ( [ callback ] ) ,
199+ ) ;
200+
201+ const listen = useCallback ( ( ) => {
202+ if ( listening . current ) {
203+ return ;
204+ }
205+
206+ if ( ! initialized . current ) {
207+ result . channel ( ) . notification ( cb ) ;
208+ }
209+
210+ listening . current = true ;
211+ initialized . current = true ;
212+ } , [ cb ] ) ;
213+
214+ const stopListening = useCallback ( ( ) => {
215+ if ( ! listening . current ) {
216+ return ;
217+ }
218+
219+ listening . current = false ;
220+ } , [ cb ] ) ;
221+
222+ useEffect ( ( ) => {
223+ listen ( ) ;
224+ } , dependencies . concat ( events ) ) ;
225+
226+ return {
227+ ...result ,
228+ /**
229+ * Stop listening for notification events
230+ */
231+ stopListening,
232+ /**
233+ * Listen for notification events
234+ */
235+ listen,
236+ } ;
237+ } ;
238+
166239export const useEchoPresence = <
167240 TPayload ,
168241 TDriver extends BroadcastDriver = BroadcastDriver ,
0 commit comments