refactor: add usePeerRoomAction hook

This commit is contained in:
Jeremy Kahn 2022-08-16 09:40:01 -05:00
parent 40b0b7047e
commit 9cc26895de
4 changed files with 20 additions and 12 deletions

View File

@ -1,25 +1,19 @@
import { useState } from 'react'
import { useParams } from 'react-router-dom'
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import { usePeerRoom } from 'hooks/usePeerRoom'
import { usePeerRoom, usePeerRoomAction, PeerActions } from 'hooks/usePeerRoom'
import { PeerRoom } from 'services/PeerRoom'
enum PeerActions {
MESSAGE = 'MESSAGE',
}
interface RoomProps {
peerRoom: PeerRoom
roomId: string
}
function Room({ peerRoom, roomId }: RoomProps) {
const { makeAction } = peerRoom
const [[sendMessage, receiveMessage]] = useState(() =>
makeAction<string>(PeerActions.MESSAGE)
const [sendMessage, receiveMessage] = usePeerRoomAction<string>(
peerRoom,
PeerActions.MESSAGE
)
receiveMessage(message => {

View File

@ -1 +1,2 @@
export * from './usePeerRoom'
export * from './usePeerRoomAction'

View File

@ -2,12 +2,12 @@ import { useEffect, useState } from 'react'
import { PeerRoom, getPeerRoom } from 'services/PeerRoom'
interface PeerRoomProps {
interface UsePeerRoomProps {
appId: string
roomId: string
}
export function usePeerRoom({ appId, roomId }: PeerRoomProps) {
export function usePeerRoom({ appId, roomId }: UsePeerRoomProps) {
const [peerRoom, setPeerRoom] = useState<PeerRoom | null>(null)
useEffect(() => {

View File

@ -0,0 +1,13 @@
import { useState } from 'react'
import { PeerRoom } from 'services/PeerRoom'
export enum PeerActions {
MESSAGE = 'MESSAGE',
}
export function usePeerRoomAction<T>(peerRoom: PeerRoom, action: PeerActions) {
const [peerRoomAction] = useState(() => peerRoom.makeAction<T>(action))
return peerRoomAction
}