Skip to content

Commit 4500f83

Browse files
committed
fix useRoomState() types to accept either a Schema or Room.
1 parent be869d0 commit 4500f83

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@colyseus/react",
3-
"version": "0.1.13",
3+
"version": "0.1.14",
44
"type": "module",
55
"scripts": {
66
"dev": "tsdown --watch --format esm,cjs",

src/schema/useRoomState.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,24 @@ import { useColyseusState } from './useColyseusState';
2929
* const players = useRoomState(room, (s) => s.players);
3030
* ```
3131
*/
32+
33+
export function useRoomState<T, U = any>(
34+
selector: (state: InferState<T, never>) => U
35+
): Snapshot<U> | undefined;
36+
3237
export function useRoomState<T = any, State = InferState<T, never>, U = State>(
3338
room: Room<T, State> | null | undefined,
34-
selector: (state: State) => U = (s) => s as unknown as U
35-
): Snapshot<U> | undefined {
39+
selector?: (state: State) => U
40+
): Snapshot<U> | undefined;
41+
42+
export function useRoomState(
43+
roomOrSelector?: Room | ((state: any) => any) | null,
44+
selector?: (state: any) => any
45+
): any {
46+
const room = typeof roomOrSelector === 'function' ? undefined : roomOrSelector;
47+
const sel = typeof roomOrSelector === 'function' ? roomOrSelector : selector;
48+
3649
const serializer = room?.serializer as SchemaSerializer<any> | undefined;
3750

38-
return useColyseusState(room?.state, serializer?.decoder, selector);
51+
return useColyseusState(room?.state, serializer?.decoder, sel);
3952
}

src/tests/useRoomState.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,20 @@ import 'reflect-metadata';
22
import { renderHook } from '@testing-library/react';
33
import { describe, expect, test } from 'vitest'
44
import { useRoomState } from '../schema/useRoomState';
5+
import { Schema, type } from '@colyseus/schema';
56

67
describe('falsy room argument', () => {
8+
test('types', () => {
9+
class MySchema extends Schema {
10+
@type("string") myField: string = "hello";
11+
}
12+
class Room {
13+
'~state': MySchema;
14+
}
15+
const schemaField = renderHook(() => useRoomState<MySchema>((s) => s.myField));
16+
const roomField = renderHook(() => useRoomState<Room>((s) => s.myField));
17+
})
18+
719
test('does not crash when room is null', () => {
820
const { result } = renderHook(() => useRoomState(null));
921
expect(result.current).toBeUndefined();

0 commit comments

Comments
 (0)