Skip to content

Commit

Permalink
network hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
luludotdev committed Oct 26, 2023
1 parent 029cd4a commit 1dec9b9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/react/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './events.ts'
export * from './inputs.ts'
export * from './network.ts'

export * from './useGame.ts'
export * from './usePlayer.ts'
27 changes: 27 additions & 0 deletions src/react/hooks/network.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type {
MessageListenerClient,
NetClient,
} from '@dreamlab.gg/core/network'
import { useEffect, useMemo } from 'https://esm.sh/react@18.2.0'
import { useGame } from './useGame.ts'

export const useNetwork = (): NetClient | undefined => {
const game = useGame()
return useMemo(() => game.client.network, [game.client.network])
}

export const useCustomMessageListener = (
channel: string,
listener: MessageListenerClient,
) => {
const network = useNetwork()

useEffect(() => {
if (!network) return
network.addCustomMessageListener(channel, listener)

return () => {
network.removeCustomMessageListener(channel, listener)
}
}, [network, channel, listener])
}

0 comments on commit 1dec9b9

Please sign in to comment.