first commit
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useUserContext } from '@/shared/context/user-context'
|
||||
import { useUserChannel } from './use-user-channel'
|
||||
|
||||
export const useBroadcastUser = () => {
|
||||
const user = useUserContext()
|
||||
const channel = useUserChannel()
|
||||
|
||||
useEffect(() => {
|
||||
channel?.postMessage(user)
|
||||
}, [channel, user])
|
||||
}
|
@@ -0,0 +1,16 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useUserChannel } from './use-user-channel'
|
||||
|
||||
export const useReceiveUser = (
|
||||
handleData: (data: Record<string, any>) => void
|
||||
) => {
|
||||
const channel = useUserChannel()
|
||||
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController()
|
||||
channel?.addEventListener('message', ({ data }) => handleData(data), {
|
||||
signal: abortController.signal,
|
||||
})
|
||||
return () => abortController.abort()
|
||||
}, [channel, handleData])
|
||||
}
|
@@ -0,0 +1,15 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
export const useUserChannel = (): BroadcastChannel | null => {
|
||||
const channelRef = useRef<BroadcastChannel | null>(null)
|
||||
|
||||
if (channelRef.current === null && 'BroadcastChannel' in window) {
|
||||
channelRef.current = new BroadcastChannel('user')
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
return () => channelRef.current?.close()
|
||||
}, [])
|
||||
|
||||
return channelRef.current
|
||||
}
|
Reference in New Issue
Block a user