Skip to content

Commit

Permalink
fix: handle msg pushing
Browse files Browse the repository at this point in the history
Signed-off-by: Azanul <azanulhaque@gmail.com>
  • Loading branch information
Azanul committed Jun 8, 2024
1 parent a3fe07b commit 4468906
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
3 changes: 1 addition & 2 deletions frontend/src/features/wuphf/Wuphf.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ import { useParams } from 'react-router-dom';
const Wuphf: React.FC = () => {
const { chatId } = useParams();
const dispatch = useDispatch<AppDispatch>();
const messages = useSelector((state: RootState) => state.wuphf.chats);
const messages = useSelector((state: RootState) => state.wuphf.chats.find((chat) => chat.chatId === chatId)?.messages);
const loading = useSelector((state: RootState) => state.wuphf.loading);
const error = useSelector((state: RootState) => state.wuphf.error);

useEffect(() => {
dispatch(fetchMessages(chatId || ''));
}, [chatId, dispatch]);

console.log(messages)
return (
<div className="container mx-auto p-4">
<h1 className="text-3xl font-bold text-center mb-6">WUPHF.com</h1>
Expand Down
18 changes: 11 additions & 7 deletions frontend/src/features/wuphf/wuphfSlice.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';

type chat = { chatId: string, messages: string[] };
type chat = { chatId: string, messages: any[] };

interface WuphfState {
chats: chat[];
Expand Down Expand Up @@ -35,7 +35,8 @@ export const fetchMessages = createAsyncThunk('wuphf/fetchMessages', async (chat
if (!response.ok) {
throw new Error('Failed to fetch chats');
}
return await response.json();
const messages = await response.json();
return { chatId, messages };
});

const wuphfSlice = createSlice({
Expand All @@ -44,10 +45,7 @@ const wuphfSlice = createSlice({
reducers: {
sendWuphf: (state, action: PayloadAction<{ chatId: string; message: string }>) => {
const { chatId, message } = action.payload;
const chat = state.chats.find((chat) => chat.chatId === chatId);
if (chat) {
chat.messages.push(message);
}
state.chats.find((chat) => chat.chatId === chatId)?.messages.push({sender: localStorage.getItem('user_id'), msg: message});
},
},
extraReducers: (builder) => {
Expand All @@ -70,7 +68,13 @@ const wuphfSlice = createSlice({
})
.addCase(fetchMessages.fulfilled, (state, action) => {
state.loading = false;
state.chats = action.payload;
const updatedChat = action.payload;
const chatIndex = state.chats.findIndex(chat => chat.chatId === updatedChat.chatId);
if (chatIndex >= 0) {
state.chats[chatIndex] = updatedChat;
} else {
state.chats.push(updatedChat);
}
})
.addCase(fetchMessages.rejected, (state, action) => {
state.loading = false;
Expand Down

0 comments on commit 4468906

Please sign in to comment.