fixed chat zustand bug
This commit is contained in:
70
apps/dispatch/app/_store/chatStore.ts
Normal file
70
apps/dispatch/app/_store/chatStore.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { create } from "zustand";
|
||||
import { ChatMessage } from "@repo/db";
|
||||
import { socket } from "(dispatch)/socket";
|
||||
|
||||
interface ChatStore {
|
||||
ownId: null | string;
|
||||
setOwnId: (id: string) => void;
|
||||
chats: Record<string, { name: string; messages: ChatMessage[] }>;
|
||||
sendMessage: (userId: string, message: string) => Promise<void>;
|
||||
addChat: (userId: string, name: string) => void;
|
||||
addMessage: (userId: string, message: ChatMessage) => void;
|
||||
}
|
||||
|
||||
export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
ownId: null,
|
||||
setOwnId: (id: string) => set({ ownId: id }),
|
||||
chats: {},
|
||||
sendMessage: (userId: string, message: string) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log("sendMessage", userId, message);
|
||||
socket.emit(
|
||||
"send-message",
|
||||
{ userId, message },
|
||||
({ error }: { error?: string }) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
},
|
||||
addChat: (userId, name) => {
|
||||
set((state) => ({
|
||||
chats: {
|
||||
...state.chats, // Bestehende Chats beibehalten
|
||||
[userId]: { name, messages: [] }, // Neuen Chat hinzufügen
|
||||
},
|
||||
}));
|
||||
},
|
||||
addMessage: (userId: string, message: ChatMessage) => {
|
||||
console.log("addMessage", userId, message);
|
||||
set((state) => {
|
||||
const user = state.chats[userId] || { name: userId, messages: [] };
|
||||
const isSender = message.senderId === state.ownId;
|
||||
|
||||
return {
|
||||
chats: {
|
||||
...state.chats,
|
||||
[userId]: {
|
||||
...user,
|
||||
name: isSender ? message.receiverName : message.senderName,
|
||||
messages: [...user.messages, message], // Neuen Zustand erzeugen
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
}));
|
||||
|
||||
socket.on(
|
||||
"chat-message",
|
||||
({ userId, message }: { userId: string; message: ChatMessage }) => {
|
||||
const store = useChatStore.getState();
|
||||
console.log("chat-message", userId, message);
|
||||
// Update the chat store with the new message
|
||||
store.addMessage(userId, message);
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user