sheva77 3 år sedan
förälder
incheckning
4bf9a71b60

+ 9 - 1
chat_final_bootstrap/src/Actions/ActionLogin.js

@@ -41,10 +41,18 @@ export const actionUserInfo = (userId) => async (dispatch) => {
         )
     );
 
-    // console.log("UserFindOne - ##########", userData.data.UserFindOne);
+    console.log("UserFindOne - ##########", userData.data.UserFindOne);
 
     if (userData && userData.data.UserFindOne) {
         dispatch(actionAuthInfo(userData.data.UserFindOne));
+
+        //
+        //
+        //
+        //
+        //
+        //
+        //
     } else {
         console.log("UserFindOne - ошибка");
     }

+ 4 - 0
chat_final_bootstrap/src/Actions/ActionsMsg.js

@@ -1,4 +1,8 @@
+//
+
 export const actionMsgAdd = (msgArr) => {
     // console.log("actionMsgAdd - ", JSON.stringify(msgArr, null, 4));
     return { type: "ADDMSG", msgs: { [msgArr[0].chat._id]: msgArr } };
 };
+
+export const actionCurChatId = (curChatId) => ({ type: "CURRENTID", curChatId });

+ 2 - 1
chat_final_bootstrap/src/Actions/index.js

@@ -1,6 +1,6 @@
 import { actionAuthLogin, actionAuthLogout, actionLogin, actionRegistration, actionUserInfo } from "./ActionLogin";
 import { gql, actionSearchMessagesByChatId, actionGetMessagesByChatId, actionSearchChat } from "./ActionsGql";
-import { actionMsgAdd } from "./ActionsMsg";
+import { actionMsgAdd, actionCurChatId } from "./ActionsMsg";
 
 export {
     actionUserInfo,
@@ -13,4 +13,5 @@ export {
     actionSearchChat,
     actionSearchMessagesByChatId,
     actionMsgAdd,
+    actionCurChatId,
 };

+ 19 - 85
chat_final_bootstrap/src/Components/ChatContain.js

@@ -2,7 +2,7 @@ import { Link } from "react-router-dom";
 import { connect } from "react-redux";
 import { useState, useEffect, useRef } from "react";
 import logo from "../images//logo23.jpg";
-import { actionSearchMessagesByChatId, actionGetMessagesByChatId } from "../Actions";
+import { actionGetMessagesByChatId } from "../Actions";
 import ScrollableFeed from "react-scrollable-feed";
 import { urlUploadConst } from "../const";
 
@@ -107,15 +107,7 @@ const MessagesList = ({ messages, myId, chatId }) => {
 
 const CMessagesList = connect(
     (s) => ({
-        //FIXME: приконнектить массив сообщений
-        chatId:
-            s.promise.MessageFind &&
-            s.promise.MessageFind.payload &&
-            s.promise.MessageFind.payload.data &&
-            s.promise.MessageFind.payload.data.MessageFind &&
-            s.promise.MessageFind.payload.data.MessageFind[0] &&
-            s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-            s.promise.MessageFind.payload.data.MessageFind[0].chat._id,
+        chatId: s.curChatId.curChatId,
         messages: s.msg,
         myId: s.auth && s.auth.payloadId,
     }),
@@ -125,11 +117,23 @@ const CMessagesList = connect(
 const Messages = ({ _id = "", messages, getMsg }) => {
     // id чата,
 
+    // console.log("Messages - id - ", _id);
+    // console.log(
+    //     "Messages - - ",
+    //     !(messages && messages[_id] && messages[_id][0] && messages[_id][0].chat && messages[_id][0].chat._id)
+    // );
+
     let avatar = messages && messages[_id] && messages[_id][0] && messages[_id][0].chat && messages[_id][0].chat.avatar;
     let title = messages && messages[_id] && messages[_id][0] && messages[_id][0].chat && messages[_id][0].chat.title;
 
     useEffect(() => {
-        if (typeof doSearchMsg === "function") getMsg(_id);
+        if (
+            typeof doSearchMsg === "function" &&
+            !(messages && messages[_id] && messages[_id][0] && messages[_id][0].chat && messages[_id][0].chat._id)
+        ) {
+            // console.log("пошли искать");
+            getMsg(_id);
+        }
     }, [_id]);
 
     // useEffect(() => {
@@ -138,12 +142,6 @@ const Messages = ({ _id = "", messages, getMsg }) => {
 
     return (
         <div className="Messages">
-            {/* <input
-                placeholder="Search message"
-                onInput={(e) => setSearchMsgStr(e.target.value)}
-                className="form-control mb-2 p-2 border border-success border-2"
-            ></input> */}
-            {/* <span>🔍</span> */}
             <div className="position-relative">
                 <div className="messagesTitle mb-3 border-bottom border-2 border-success p-2 roundIcon">
                     {avatar && avatar.url ? (
@@ -177,74 +175,10 @@ const Messages = ({ _id = "", messages, getMsg }) => {
     );
 };
 
-const CMessages = connect(
-    (s) => ({
-        //id чата
-        _id:
-            s.promise.MessageFind &&
-            s.promise.MessageFind.payload &&
-            s.promise.MessageFind.payload.data &&
-            s.promise.MessageFind.payload.data.MessageFind &&
-            s.promise.MessageFind.payload.data.MessageFind[0] &&
-            s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-            s.promise.MessageFind.payload.data.MessageFind[0].chat._id,
-        messages: s.msg,
-        //     s.promise.chatFindOne.payload &&
-        //     s.promise.chatFindOne.payload.data &&
-        //     s.promise.chatFindOne.payload.data.ChatFindOne &&
-        //     s.promise.chatFindOne.payload.data.ChatFindOne.messages,
-        // avatar:
-        //     s.promise.MessageFind &&
-        //     s.promise.MessageFind.payload &&
-        //     s.promise.MessageFind.payload.data &&
-        //     s.promise.MessageFind.payload.data.MessageFind &&
-        //     s.promise.MessageFind.payload.data.MessageFind[0] &&
-        //     s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-        //     s.promise.MessageFind.payload.data.MessageFind[0].chat.avatar,
-        // title:
-        //     s.promise.MessageFind &&
-        //     s.promise.MessageFind.payload &&
-        //     s.promise.MessageFind.payload.data &&
-        //     s.promise.MessageFind.payload.data.MessageFind &&
-        //     s.promise.MessageFind.payload.data.MessageFind[0] &&
-        //     s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-        //     s.promise.MessageFind.payload.data.MessageFind[0].chat.title,
-    }),
-    { getMsg: actionGetMessagesByChatId }
-)(Messages);
-
-// const CMessagesList = connect((s) => ({
-//     //id чата
-//     _id:
-//         s.promise.MessageFind &&
-//         s.promise.MessageFind.payload &&
-//         s.promise.MessageFind.payload.data &&
-//         s.promise.MessageFind.payload.data.MessageFind &&
-//         s.promise.MessageFind.payload.data.MessageFind[0] &&
-//         s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-//         s.promise.MessageFind.payload.data.MessageFind[0].chat._id,
-//     arrayOfMessages:
-//         s.promise.MessageFind &&
-//         s.promise.MessageFind.payload &&
-//         s.promise.MessageFind.payload.data &&
-//         s.promise.MessageFind.payload.data.MessageFind,
-//     avatar:
-//         s.promise.MessageFind &&
-//         s.promise.MessageFind.payload &&
-//         s.promise.MessageFind.payload.data &&
-//         s.promise.MessageFind.payload.data.MessageFind &&
-//         s.promise.MessageFind.payload.data.MessageFind[0] &&
-//         s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-//         s.promise.MessageFind.payload.data.MessageFind[0].chat.avatar,
-//     title:
-//         s.promise.MessageFind &&
-//         s.promise.MessageFind.payload &&
-//         s.promise.MessageFind.payload.data &&
-//         s.promise.MessageFind.payload.data.MessageFind &&
-//         s.promise.MessageFind.payload.data.MessageFind[0] &&
-//         s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-//         s.promise.MessageFind.payload.data.MessageFind[0].chat.title,
-// }))(MessagesList);
+const CMessages = connect((s) => ({ _id: s.curChatId.curChatId, messages: s.msg }), {
+    getMsg: actionGetMessagesByChatId,
+})(Messages);
+// - id chata
 
 export const ChatContain = ({ _chatId = "" }) => (
     <div className="ChatContain">

+ 6 - 10
chat_final_bootstrap/src/Components/ChatsList.js

@@ -8,11 +8,12 @@ import history from "../history";
 import { useEffect } from "react";
 import { useState } from "react";
 
-const CCounter = connect;
+// const CCounter = connect;
 
 const ChatItem = ({ _id = "", avatar, title, messages, userId, currentChatId }) => {
     // здесь _id, avatar, title - чата,
     // currentChatId - текущий выбраный чат
+    // console.log("ChatItem - ", _id, currentChatId);
 
     return (
         <Link to={`/main/${_id}`} className="noUnderLine">
@@ -62,6 +63,8 @@ const ChatItem = ({ _id = "", avatar, title, messages, userId, currentChatId })
 };
 
 const List = ({ arrayOfChats, userId, currentChatId }) => {
+    // console.log(arrayOfChats);
+    // arrayOfChats - массив всех чатов пользователя
     if (!arrayOfChats) return <></>;
 
     // сортируем чаты так, чтобы сверху показывались чаты, в которых последнее сообщение "свежее" всех остальных
@@ -87,6 +90,7 @@ const List = ({ arrayOfChats, userId, currentChatId }) => {
     });
 
     // console.log("chatsList - arrayOfChats.sort: ", arrayOfChats);
+    // console.log("chatsList - : ", currentChatId);
 
     return (
         <ul className="list-group" role="tablist">
@@ -98,15 +102,7 @@ const List = ({ arrayOfChats, userId, currentChatId }) => {
 };
 
 const CList = connect((s) => ({
-    currentChatId:
-        s.promise &&
-        s.promise.MessageFind &&
-        s.promise.MessageFind.payload &&
-        s.promise.MessageFind.payload.data &&
-        s.promise.MessageFind.payload.data.MessageFind &&
-        s.promise.MessageFind.payload.data.MessageFind[0] &&
-        s.promise.MessageFind.payload.data.MessageFind[0].chat &&
-        s.promise.MessageFind.payload.data.MessageFind[0].chat._id,
+    currentChatId: s.curChatId && s.curChatId.curChatId,
 
     //FIXME: для сортировки надо подсоеденить правильный массив
     arrayOfChats: s.auth && s.auth.chats,

+ 39 - 24
chat_final_bootstrap/src/Pages/PageMain.js

@@ -2,48 +2,63 @@ import { ChatContain } from "../Components";
 import { Sidebar } from "../Layout";
 import { store } from "../Reducers";
 import history from "../history";
-import { actionGetMessagesByChatId, actionSearchChat, actionSearchMessagesByChatId } from "../Actions";
+import { actionSearchMessagesByChatId, actionCurChatId } from "../Actions";
 import { connect } from "react-redux";
 import { useState, useEffect } from "react";
 
 //prettier-ignore
 const PageMain = ({
-    match: {params: { _chatId }},
+    match: {
+        params: { _chatId },
+    },
     _userId,
-    // getChatList = null,
+    messages, // из редакса через коннект
     getMesagesList = null,
+    setCurId = null, // из редакса через коннект
 }) => {
-    // console.log("PageMain.js. - True _chatId: ", _chatId);
-
-    // useEffect(() => {
-    //     if (typeof getChatList === "function") {
-    //         getChatList(_userId);
-    //     }
-    // }, [_userId]);
+    // console.log(_chatId);
+    // console.log(messages);
 
+if (
+    !_userId ||
+    !store.getState().auth ||
+    !store.getState().auth.login ||
+    _userId !== store.getState().auth.payloadId
+) {
+    history.push("/");
+}
+    //
+    //
+    //
+    //
+    //
+    //
+    //FIXME:  не посылать запрос если меседжи есть
+    //завести редакс для курент_ид
+    //
+    //
+    //
+    //
+    //
     useEffect(() => {
-        if (typeof getMesagesList === "function" && _chatId) {
+        if (
+            typeof getMesagesList === "function" &&
+            _chatId &&
+            !(messages && messages[_chatId] && messages[_chatId][0])
+        ) {
             getMesagesList(_chatId);
         }
+        if (typeof setCurId === "function") setCurId(_chatId);
     }, [_chatId]);
 
-
-    if (
-        //FIXME: надо засунуть router в redux
-        !_userId ||
-        !store.getState().auth ||
-        !store.getState().auth.login ||
-        _userId !== store.getState().auth.payloadId
-    ) {
-        history.push("/");
-    }
     
+
     return (
         <div className="PageMain container-fluid">
             <div className="row g-3">
                 <div className="col-md-4">
                     {/* {_userId + ` - подмена id`} */}
-                    <Sidebar/>
+                    <Sidebar />
                 </div>
                 <div className="col-md-8 fonRomaska">
                     <ChatContain _chatId={_chatId} />
@@ -54,7 +69,7 @@ const PageMain = ({
 };
 
 // prettier-ignore
-export const CPageMain = connect((s) => ({ _userId: s.auth && s.auth.payloadId }), {
-    // getChatList: actionSearchChat,
+export const CPageMain = connect((s) => ({ _userId: s.auth && s.auth.payloadId, messages: s.msg }), {
+    setCurId: actionCurChatId,
     getMesagesList: actionSearchMessagesByChatId,
 })(PageMain);

+ 9 - 1
chat_final_bootstrap/src/Reducers/index.js

@@ -63,6 +63,14 @@ function msgReduser(state = {}, action) {
     return state;
 }
 
+function currentChatIdReduser(state = {}, action) {
+    if (["LOGOUT", "LOGIN"].includes(action.type)) return {}; // кликнули по новому чату в sideBar
+    if (action.type === "CURRENTID") {
+        return { curChatId: action.curChatId };
+    }
+    return state;
+}
+
 function promiseReducer(state = {}, action) {
     if (["LOGOUT", "LOGIN"].includes(action.type)) return {};
     if (action.type === "PROMISE") {
@@ -100,7 +108,7 @@ export const actionPromise = (name, promise) => {
 };
 
 export const store = createStore(
-    combineReducers({ auth: authReducer, promise: promiseReducer, msg: msgReduser }),
+    combineReducers({ auth: authReducer, promise: promiseReducer, msg: msgReduser, curChatId: currentChatIdReduser }),
     applyMiddleware(thunk)
 );