chore: migrate to reducer pattern instead of useState

This commit is contained in:
Alexander Daichendt 2025-02-12 11:33:48 +01:00
parent 18dd8b83f0
commit 7150ca87c3
7 changed files with 85 additions and 29 deletions

View file

@ -1,17 +1,36 @@
import { createContext, useContext } from "react";
import { createContext, useContext, Dispatch } from "react";
import { ChatMessage, User } from "../../../shared";
interface ChatContextType {
export type ChatState = {
messages: ChatMessage[];
currentUser: User | null;
isConnected: boolean;
};
export type ChatAction =
| { type: "ADD_MESSAGE"; payload: ChatMessage }
| { type: "SET_USER"; payload: User }
| { type: "SET_CONNECTED"; payload: boolean }
| { type: "CLEAR_MESSAGES" };
export type ChatActions = {
addMessage: (message: ChatMessage) => void;
setCurrentUser: (user: User) => void;
setUser: (user: User) => void;
setConnected: (isConnected: boolean) => void;
};
interface ChatContextType {
state: ChatState;
dispatch: Dispatch<ChatAction>;
actions: ChatActions;
}
export const ChatContext = createContext<ChatContextType | null>(null);
export const useChatState = () => {
const context = useContext(ChatContext);
if (!context) throw new Error("useChat must be used within ChatProvider");
if (!context) {
throw new Error("useChatState must be used within ChatProvider");
}
return context;
};