Added server messages handling
This commit is contained in:
parent
633220dbce
commit
dcdc49e8e0
@ -3,7 +3,13 @@ import { createContext, FC, useContext, useEffect, useState } from "react";
|
|||||||
|
|
||||||
import { defaultState } from "./constants";
|
import { defaultState } from "./constants";
|
||||||
import { ContextData, ContextValue } from "./types/context";
|
import { ContextData, ContextValue } from "./types/context";
|
||||||
import { isArrayOf, isMessage, isRoom } from "@roomruler/messages";
|
import {
|
||||||
|
composeMessage,
|
||||||
|
isListMessage,
|
||||||
|
isMessage,
|
||||||
|
isUpdateMessage,
|
||||||
|
UpdateMessage,
|
||||||
|
} from "@roomruler/messages";
|
||||||
import { WS_URL } from "./config";
|
import { WS_URL } from "./config";
|
||||||
import { RoomDisplay, RoomState } from "./types/room";
|
import { RoomDisplay, RoomState } from "./types/room";
|
||||||
|
|
||||||
@ -14,12 +20,22 @@ const ws = new WebSocket(WS_URL);
|
|||||||
export const RoomContextProvider: FC = ({ children }) => {
|
export const RoomContextProvider: FC = ({ children }) => {
|
||||||
const [state, setState] = useState<ContextData>(defaultState);
|
const [state, setState] = useState<ContextData>(defaultState);
|
||||||
|
|
||||||
const toggleFree = (index: number) => {};
|
const toggleFree = (id: number) => {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify(
|
||||||
|
composeMessage<UpdateMessage>("update", {
|
||||||
|
id,
|
||||||
|
value: !state.char[state.ids[id]].free,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
ws.onmessage = ({ data }) => {
|
ws.onmessage = ({ data }) => {
|
||||||
const message: unknown = JSON.parse(data);
|
const message: unknown = JSON.parse(data);
|
||||||
if (isMessage(message) && isArrayOf(message.args, isRoom)) {
|
if (isMessage(message)) {
|
||||||
|
if (isListMessage(message)) {
|
||||||
const map: RoomDisplay[] = [],
|
const map: RoomDisplay[] = [],
|
||||||
char: RoomState[] = [],
|
char: RoomState[] = [],
|
||||||
ids: Record<number, number> = {};
|
ids: Record<number, number> = {};
|
||||||
@ -39,6 +55,16 @@ export const RoomContextProvider: FC = ({ children }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setState({ map, char, ids });
|
setState({ map, char, ids });
|
||||||
|
} else if (isUpdateMessage(message)) {
|
||||||
|
setState(
|
||||||
|
produce((draft) => {
|
||||||
|
const { id, value } = message.args;
|
||||||
|
const index = draft.ids[id];
|
||||||
|
|
||||||
|
draft.char[index].free = value;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user