Spaces:
Paused
Paused
File size: 1,861 Bytes
a0fda44 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
import useFetch from "./useFetch";
import { useDispatch, useSelector } from "react-redux";
import { chatActions } from "../store/chatSlice";
import { chatListActions } from "../store/chatListSlice";
const useChat = (contact, from = "contact") => {
const mode = useSelector((state) => state.chatReducer.mode);
const dispatch = useDispatch();
const chatHistory = useSelector((state) => state.chatReducer.chatHistory);
const chat = useSelector((state) => state.chatReducer.currentChatRoom);
// Fetch chat room request
const { reqFn: fetchChatRoom } = useFetch(
{
method: "GET",
url: `/chatRoom/${contact?.chatRoomId}`,
},
(data) => {
const chatRoom = {
chatProfile:
from === "contact"
? {
...contact.contactDetails,
name: contact.contactName,
}
: { ...contact.profile },
...data.data.chatRoom,
};
// Set chat room as current
dispatch(chatActions.setChatRoom({ chatRoom }));
// Add chat room to history
dispatch(
chatActions.addToChatRoomHistory({
chatRoomId: contact.chatRoomId,
chatRoom,
})
);
}
);
// Set chat room
const setChatRoom = async (
{ disableSettingChatRoomActive } = { disableSettingChatRoomActive: false }
) => {
// Check if chat has been fetched already
const chatRoom = chatHistory[contact.chatRoomId];
if (chatRoom) {
dispatch(chatActions.setChatRoom({ chatRoom }));
} else {
await fetchChatRoom();
}
!disableSettingChatRoomActive && dispatch(chatActions.setChatActive());
dispatch(
chatListActions.markMessagesInChatRoomAsRead({
chatRoomId: contact.chatRoomId,
})
);
};
return { chat, setChatRoom, mode, chatActions };
};
export default useChat;
|