|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import React, { Dispatch, createContext, useContext, useReducer } from "react"; |
| 4 | +import { ChatRoom } from "@/types/chat"; |
| 5 | + |
| 6 | +interface ChatStateTypes { |
| 7 | + rooms: ChatRoom[], |
| 8 | + unreadCount: number, |
| 9 | + error: string, |
| 10 | + loading: boolean, |
| 11 | +} |
| 12 | + |
| 13 | +const initialChatState: ChatStateTypes = { |
| 14 | + rooms: new Array<ChatRoom>, |
| 15 | + unreadCount: 0, |
| 16 | + error: "", |
| 17 | + loading: false, |
| 18 | +} |
| 19 | + |
| 20 | +const ChatContext = createContext<ChatStateTypes>(initialChatState); |
| 21 | +const ChatDispatchContext = createContext<Dispatch<any>>(() => { }); |
| 22 | + |
| 23 | +export const CHATROOMS_LOADED = "CHATROOMS_LOADED"; |
| 24 | +export const ERROR_LOADING_ROOMS = "ERROR_LOADING_ROOMS"; |
| 25 | +export const NEW_CHATROOM = "NEW_CHATROOM"; |
| 26 | +export const CHATROOM_DELETED = "CHATROOM_DELETED"; |
| 27 | +export const NEW_MESSAGE_IN_CHATROOM = "NEW_MESSAGE_IN_CHATROOM"; |
| 28 | +export const CHATROOM_READ = "CHATROOM_READ" |
| 29 | + |
| 30 | +function StudentCourseReducer(ChatState: ChatStateTypes, actionPayload: any): ChatStateTypes { |
| 31 | + switch (actionPayload.type) { |
| 32 | + case CHATROOMS_LOADED: |
| 33 | + return { |
| 34 | + rooms: actionPayload.rooms, |
| 35 | + error: "", |
| 36 | + loading: false, |
| 37 | + unreadCount: actionPayload.unreadCount, |
| 38 | + } |
| 39 | + case ERROR_LOADING_ROOMS: |
| 40 | + return { |
| 41 | + ...ChatState, |
| 42 | + error: actionPayload.error, |
| 43 | + } |
| 44 | + case NEW_CHATROOM: |
| 45 | + return { |
| 46 | + ...ChatState, |
| 47 | + } |
| 48 | + case CHATROOM_DELETED: |
| 49 | + return { |
| 50 | + ...ChatState, |
| 51 | + } |
| 52 | + case NEW_MESSAGE_IN_CHATROOM: |
| 53 | + return { |
| 54 | + ...ChatState, |
| 55 | + } |
| 56 | + case CHATROOM_READ: |
| 57 | + return { |
| 58 | + ...ChatState, |
| 59 | + } |
| 60 | + default: |
| 61 | + return ChatState; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +export function ChatProvider({ children }: { |
| 66 | + children: React.ReactElement |
| 67 | +}) { |
| 68 | + const [Chat, dispatch] = useReducer(StudentCourseReducer, initialChatState); |
| 69 | + |
| 70 | + return ( |
| 71 | + <ChatContext.Provider value={Chat}> |
| 72 | + <ChatDispatchContext.Provider value={dispatch}> |
| 73 | + {children} |
| 74 | + </ChatDispatchContext.Provider> |
| 75 | + </ChatContext.Provider> |
| 76 | + ); |
| 77 | +} |
| 78 | + |
| 79 | +export function useChat() { |
| 80 | + return useContext(ChatContext); |
| 81 | +} |
| 82 | + |
| 83 | +export function useChatDispatch() { |
| 84 | + return useContext(ChatDispatchContext); |
| 85 | +} |
| 86 | + |
0 commit comments