integrated redux library

This commit is contained in:
Nikolai Petukhov 2024-10-16 23:40:34 +03:00
parent fde1f8ecfe
commit 59d4a44079
2 changed files with 35 additions and 21 deletions

View File

@ -25,13 +25,11 @@ export const apiSlice = createApi({
query: (username) => `/chat/list/${username}`,
}),
postChat: builder.mutation({
query: (body) => ({
url: '/chat/post',
query: ({ id1, id2 }) => ({
url: `/chat/item/${id1}/${id2}`,
method: 'POST',
body,
}),
}),
// Add more endpoints as needed
}),
});

View File

@ -28,22 +28,29 @@ const Home = () => {
if (getError) {
displayMessage(getError.message, MessageType.ERROR);
}
}, [getError]);
if (getError) {
displayMessage(getError.message, MessageType.ERROR);
}
}, [getError, postError]);
useEffect(() => {
if (chatsData) {
setChats(chatsData.chats);
// setChats(chatsData.chats);
let data = chatsData.chats;
try {
// const sortedChats = chatsData.chats.sort((a, b) => {
// const lastMessageA = new Date(a.timestamp);
// const lastMessageB = new Date(b.timestamp);
// return lastMessageB - lastMessageA;
// });
// //
// // console.log('sorted:', sortedChats);
//
// setChats(sortedChats);
const sortedChats = [...data].sort((a, b) => {
const lastMessageA = a.messages[a.messages.length - 1];
const lastMessageB = b.messages[b.messages.length - 1];
const dateA = new Date(lastMessageA.timestamp);
const dateB = new Date(lastMessageB.timestamp);
return dateB - dateA;
});
setChats(sortedChats);
} catch (e) {
console.error(e);
}
@ -60,7 +67,7 @@ const Home = () => {
displayMessage("Sent", MessageType.INFO);
try {
const data = await createChat({ alias, username }).unwrap(); // Using unwrap to handle promise rejection
const data = await createChat({ id1: alias, id2: username }).unwrap(); // Using unwrap to handle promise rejection
localStorage.setItem("message", "Successfully opened chat!");
localStorage.setItem("interlocutorId", alias);
window.location.href = URLs.chat.url;
@ -69,8 +76,6 @@ const Home = () => {
}
};
if (isGetting) return <div>Loading...</div>;
return (
<div className="homeWrapper">
<div className="headerPos">
@ -85,13 +90,24 @@ const Home = () => {
value={interlocutor}
setValue={setInterlocutor}
placeholder="Enter the username (id)"
enter={createChatHandler}
submit={interlocutor}
/>
</div>
{isGetting ? (
<div>Loading...</div>
) : (
<>
<Search search={createChatHandler} item={interlocutor} />
<p>Your chats</p>
<ChatsList chats={chats} /> {/* Retained original variable name */}
<ChatsList chats={chats} />
</>
)}
</div>
);
};