Browse Source

Add addCommentOnePostWatcher, changeLikePostWatcher and change postReducer

LenDoc 2 years ago
parent
commit
38c5195c23

+ 36 - 61
src/actions/index.js

@@ -332,7 +332,6 @@ export const actionOnePost = (_id) =>
          _id, createdAt, text  owner{_id login avatar{_id url}}
          answers{
            _id, createdAt, text owner{_id login  avatar{_id url}}
-          
          }
        owner{_id login avatar{_id url}}}
        likes{
@@ -340,10 +339,7 @@ export const actionOnePost = (_id) =>
          owner{				
             _id login avatar {_id url}
            }
-     }
-       
- }
-     }
+     }}}
 
       `,
       {
@@ -352,10 +348,9 @@ export const actionOnePost = (_id) =>
     ),
   )
 
-export const actionFindLikes = (_id) => async (dispatch) => {
-  await dispatch(
+export const actionFindLikes = (_id) => 
     actionPromise(
-      'onePostFindLike',
+      'onePostLikes',
       gql(
         `query OneFind($post:String){
          PostFindOne(query:$post){
@@ -371,12 +366,9 @@ export const actionFindLikes = (_id) => async (dispatch) => {
           post: JSON.stringify([{ _id }]),
         },
       ),
-    ),
-  )
-}
+    )
 
-export const actionAllFollowers = (_id) => async (dispatch) => {
-  await dispatch(
+export const actionAllFollowers = (_id) => 
     actionPromise(
       'allFollowers',
       gql(
@@ -390,12 +382,9 @@ export const actionAllFollowers = (_id) => async (dispatch) => {
           userId: JSON.stringify([{ _id }]),
         },
       ),
-    ),
-  )
-}
+    )
 
-export const actionAllFollowing = (_id) => async (dispatch) => {
-  await dispatch(
+export const actionAllFollowing = (_id) =>
     actionPromise(
       'allFollowing',
       gql(
@@ -409,11 +398,10 @@ export const actionAllFollowing = (_id) => async (dispatch) => {
           userId: JSON.stringify([{ _id }]),
         },
       ),
-    ),
-  )
-}
-export const actionAddComment = (postId, text) => async (dispatch) => {
-  await dispatch(
+    )
+  
+export const actionAddComment = (postId, text) => 
+
     actionPromise(
       "addComment",
       gql(
@@ -430,13 +418,11 @@ export const actionAddComment = (postId, text) => async (dispatch) => {
             post: {
               _id: postId,
             },
-            text: text,
+            text
           },
         },
       ),
-    ),
-  )
-}
+    )
 
 export const actionGetCommentsOnePost = (postId) =>
     actionPromise('commentsOnePost', gql(`query commentFindPost ($id:String!){
@@ -455,8 +441,7 @@ export const actionGetCommentsOnePost = (postId) =>
     }`, { id: JSON.stringify([{ _id: postId }]) }))
 
 
-export const actionAddSubComment = (commentId, comment) => async (dispatch) => {
-  await dispatch(
+export const actionAddSubComment = (commentId, comment) =>
     actionPromise(
       'addSubComment',
       gql(
@@ -477,9 +462,7 @@ export const actionAddSubComment = (commentId, comment) => async (dispatch) => {
           },
         },
       ),
-    ),
-  )
-}
+    )
 
 // export const actionAddFullComment = (postId,comment) => async(dispatch) => {
 //   let addComment = await dispatch(actionAddComment(postId,comment));
@@ -539,7 +522,7 @@ export const actionAddLike = (postId) =>
       `mutation AddLike($like:LikeInput){
           LikeUpsert(like:$like)
           {
-            _id owner{_id login}
+            _id
           }
         }`,
       {
@@ -552,8 +535,7 @@ export const actionAddLike = (postId) =>
     ),
   )
 
-export const actionGetFindLiked = (_id) => async (dispatch) => {
-  await dispatch(
+export const actionGetFindLiked = (_id) => 
     actionPromise(
       'findLiked',
       gql(
@@ -568,9 +550,7 @@ export const actionGetFindLiked = (_id) => async (dispatch) => {
           id: JSON.stringify([{ 'post._id': _id }]),
         },
       ),
-    ),
-  )
-}
+    )
 
 // export const actionDeleteFullLike = (likeId) => async(dispatch,getState) => {
 //   let unLike = await dispatch(actionDeleteLike(likeId));
@@ -579,21 +559,21 @@ export const actionGetFindLiked = (_id) => async (dispatch) => {
 //   }
 // }
 
-export const actionDeleteFullLike = (likeId, postId) => async (
-  dispatch,
-  getState,
-) => {
-  await dispatch(actionDeleteLike(likeId, postId))
-  const {
-    promise: {
-      deleteLike: { status },
-    },
-  } = getState()
-  if (status === 'FULFILLED') {
-    await dispatch(actionOnePost(postId))
-  }
-  //  await dispatch(actionOnePost(postId));
-}
+// export const actionDeleteFullLike = (likeId, postId) => async (
+//   dispatch,
+//   getState,
+// ) => {
+//   await dispatch(actionDeleteLike(likeId, postId))
+//   const {
+//     promise: {
+//       deleteLike: { status },
+//     },
+//   } = getState()
+//   if (status === 'FULFILLED') {
+//     await dispatch(actionOnePost(postId))
+//   }
+//   //  await dispatch(actionOnePost(postId));
+// }
 export const actionDeleteLike = (likeId, postId) =>
   actionPromise(
     'deleteLike',
@@ -601,9 +581,7 @@ export const actionDeleteLike = (likeId, postId) =>
       `mutation DeleteLike($like:LikeInput){
           LikeDelete(like: $like)
           {
-            _id, post{
-              _id owner{_id login avatar{_id url}}
-            }
+            _id
           }
         }`,
       {
@@ -748,8 +726,7 @@ export const actionExplorePostsCount = () =>
       },
     ),
   )
-export const actionSearchUser = (userName) => async (dispatch) => {
-  await dispatch(
+export const actionSearchUser = (userName) =>
     actionPromise(
       'searchUser',
       gql(
@@ -770,9 +747,7 @@ export const actionSearchUser = (userName) => async (dispatch) => {
           ]),
         },
       ),
-    ),
-  )
-}
+    )
 
 export const actionUserUpsert = (user, myId) =>
   actionPromise(

+ 8 - 0
src/actions/typeSaga/postActionSaga.js

@@ -0,0 +1,8 @@
+export const actionFullOnePostSaga = (_id) => ({
+    type:"ONE_POST", _id
+  })
+export const actionAddFullCommentSaga = (postId, text) => ({
+    type:"ONE_POST_COMMENT", postId, text
+    
+  })
+  

+ 10 - 0
src/actions/types/postActionTypes.js

@@ -0,0 +1,10 @@
+
+export const actionOnePostType = (onePost) => ({ type: 'POST', onePost })
+export const actionClearOnePostType = () => ({ type: 'CLEAR_ONE_POST' })
+export const actionChangeLikeType = (newResult) => ({
+    type:"CHANGE_LIKE", newResult
+    
+  })
+  export const actionAddCommentType = (newResult) => ({
+    type:"ADD_COMMENT", newResult
+  })

+ 11 - 12
src/components/Like.js

@@ -6,8 +6,7 @@ import { HeartOutlined, HeartFilled } from '@ant-design/icons'
 import React, { useState } from 'react'
 import { LinkToUser } from './LinkToUser'
 import {
-  actionAddFullLikeFeed,
-  actionDeleteFullLikeFeed,
+  actionChangeLike
 } from '../redux/saga'
 import { connect } from 'react-redux'
 
@@ -29,12 +28,13 @@ export const Like = ({
   addLike,
   deleteLike,
   likes = [],
+  changeLike,
   children,
 }) => {
   const likeId = likes.find((like) => like?.owner?._id === my_Id)?._id
-  const changeLike = () =>
-    likeId ? deleteLike(likeId, postId) : addLike(postId)
-
+  // const changeLike = () =>
+  //   likeId ? deleteLike(likeId, postId) : addLike(postId)
+console.log('like id in component', likeId)
   const [isModalVisible, setIsModalVisible] = useState(false)
 
   const showModal = () => {
@@ -43,7 +43,8 @@ export const Like = ({
   return (
     <>
       <div style={{ display: 'flex' }}>
-        <h2 onClick={changeLike}>
+        <h3 onClick={() => changeLike(likeId, postId)}>
+       
           {likeId ? (
             <HeartFilled
               style={{ cursor: 'pointer', fontSize: 'xx-large', color: 'red' }}
@@ -53,7 +54,7 @@ export const Like = ({
               style={{ cursor: 'pointer', fontSize: 'xx-large' }}
             />
           )}
-        </h2>
+        </h3>
         {likes.length ? (
           <h3 style={{ cursor: 'pointer', paddingLeft: 8 }} onClick={showModal}>
             {' '}
@@ -73,13 +74,12 @@ export const Like = ({
     </>
   )
 }
-const AllLikeComponent = ({ my_Id, addLike, deleteLike, likes, postId }) => (
+const AllLikeComponent = ({ my_Id, likes,changeLike, postId }) => (
   <Like
     my_Id={my_Id}
-    addLike={addLike}
-    deleteLike={deleteLike}
     likes={likes}
     postId={postId}
+    changeLike={changeLike}
   >
     <Likes likes={likes} />
   </Like>
@@ -90,7 +90,6 @@ export const CLike = connect(
     my_Id: state.auth?.payload?.sub?.id || '',
   }),
   {
-    addLike: actionAddFullLikeFeed,
-    deleteLike: actionDeleteFullLikeFeed,
+    changeLike: actionChangeLike
   },
 )(AllLikeComponent)

+ 9 - 8
src/components/Post.js

@@ -1,6 +1,5 @@
 import { Link } from 'react-router-dom'
 import {
-  actionAddFullComment,
   actionAddSubFullComment,
   actionDeleteFullLike,
   actionAddFullLike,
@@ -12,7 +11,8 @@ import { connect } from 'react-redux'
 import { Row, Col } from 'antd'
 import { CComments, AddComment } from './Comment'
 import { CPostEditor } from '../pages/createAndEditPost'
-import { actionFullOnePost } from '../redux/reducers/post/postReducer'
+
+import { actionFullOnePostSaga,actionAddFullCommentSaga } from '../actions/typeSaga/postActionSaga'
 import { CLike} from './Like'
 import { ConstructorModal } from '../helpers'
 import React, { useState, useEffect } from 'react'
@@ -21,6 +21,7 @@ import {
 } from '../redux/saga'
 import { LinkToUser } from './LinkToUser'
 import { MyCarousel } from './Carousel'
+
 const EditMyPost = ({ _id }) => {
   return (
     <>
@@ -95,14 +96,14 @@ export const PagePost = ({
           <h2> Text: {onePost?.text || ''} </h2>
           <Divider>Comments</Divider>
           <div className="Scroll">
-            {/* <CComments
+            <CComments
               postId={onePost?._id}
               comments={onePost?.comments || []}
-            /> */}
+            />
           </div>
           <div style={{ display: 'flex', margin: '40px 10px' }}>
-            {/* <CLike likes={onePost?.likes} postId={onePost?._id} />
-            <AddComment addComment={addComment} postId={onePost?._id} /> */}
+            <CLike likes={onePost?.likes} postId={onePost?._id} />
+            <AddComment addComment={addComment} postId={onePost?._id} />
           </div>
         </Col>
       </Row>
@@ -118,9 +119,9 @@ export const CPost = connect(
     addComment: state.promise?.addComment?.payload,
   }),
   {
-    // addComment: actionAddFullCommentFeed,
+    addComment: actionAddFullCommentSaga,
     // addCommentReply: actionAddSubFullComment,
-    onPost: actionFullOnePost,
+    onPost: actionFullOnePostSaga,
   },
 )(PagePost)
 

+ 2 - 2
src/pages/createAndEditPost/index.js

@@ -6,7 +6,7 @@ import {
   actionPostUpsert,
   actionClearPromise,
 } from '../../actions'
-import { actionClearPostsOne } from '../../redux/reducers/post/postReducer'
+import { actionClearOnePostType } from '../../actions/types/postActionTypes'
 import { Button, message } from 'antd'
 import {
   Dropzone
@@ -198,7 +198,7 @@ export const CPostEditor = connect(
   {
     onSave: actionPostUpsert,
     onFileDrop: actionUploadFiles,
-    clearPostOne: actionClearPostsOne,
+    clearPostOne: actionClearOnePostType,
     clearPromise: actionClearPromise,
   },
 )(PostEditor)

+ 12 - 12
src/pages/feedPosts/index.js

@@ -2,8 +2,8 @@ import React, { useMemo, useState, useEffect } from 'react'
 import {
   actionAllPostsFeed,
   actionFullAllGetPosts,
-  actionAddFullComment,
-  actionFindSubComment,
+  // actionAddFullComment,
+  // actionFindSubComment,
   actionAddSubFullComment,
   actionFindLikes,
   actionGetFindLiked,
@@ -15,9 +15,9 @@ import {
 import {
   actionFullFeed,
 
-  actionAddFullCommentFeed,
-  actionAddFullLikeFeed,
-  actionDeleteFullLikeFeed,
+  // actionAddFullCommentFeed,
+  // actionAddFullLikeFeed,
+  // actionDeleteFullLikeFeed,
  
 } from '../../redux/saga'
 import {actionClearFeedPosts} from '../../redux/reducers/feed/feedReducer'
@@ -98,16 +98,16 @@ const MyPostFeed = ({
                     <h1  className='Title'> Text: {text || ''}</h1>
                     <Divider>Comments</Divider>
                     <div className="ScrollForFeed">
-                      <CCommentsForFeed
+                      {/* <CCommentsForFeed
                         postId={_id}
                         comments={comments || []}
-                      />
+                      /> */}
                       </div>
                       <center>
                       <div style={{ display: 'flex', padding: '20px', marginLeft:'100px' }}>
                         {/* <CLikeForFeed likes={likes} postId={_id} /> */}
 
-                        <AddComment addComment={addComment} postId={_id} />
+                        {/* <AddComment addComment={addComment} postId={_id} /> */}
                       </div>
                        </center>
                     </div>
@@ -133,7 +133,7 @@ const CCommentsForFeed = connect(
     // addSubComment: state.promise?.addSubComment,
   }),
   {
-    addComment: actionAddFullCommentFeed,
+    // addComment: actionAddFullCommentFeed,
     // addCommentReply: actionAddSubFullComment,
     // findSubComment: actionFindSubComment,
   },
@@ -149,7 +149,7 @@ export const CPostForFeed = connect(
   {
     onPostsFeed: actionFullAllGetPosts,
     onClearFeed: actionClearFeedPosts,
-    addComment: actionAddFullCommentFeed,
+    // addComment: actionAddFullCommentFeed,
     // addCommentReply: actionAddSubFullComment,
     // addLike: actionAddFullLikeForFeed,
 
@@ -174,7 +174,7 @@ export const CLikeForFeed = connect(
     deleteLike: state.promise?.deleteLike?.payload,
   }),
   {
-    addLike: actionAddFullLikeFeed,
-    deleteLike: actionDeleteFullLikeFeed,
+    // addLike: actionAddFullLikeFeed,
+    // deleteLike: actionDeleteFullLikeFeed,
   },
 )(AllLikeComp)

+ 6 - 3
src/redux/reducers/index.js

@@ -15,7 +15,9 @@ import {
   feedWatcher,
   exploreWatcher,
 onePostWatcher,
-  addCommentFeedWatcher
+  addCommentFeedWatcher,
+  addCommentOnePostWatcher,
+  changeLikePostWatcher
 } from '../saga'
 import createSagaMiddleware from 'redux-saga' //функция по созданию middleware
 import {
@@ -48,8 +50,9 @@ function* rootSaga() {
     fullPageAboutUserWatcher(),
     feedWatcher(),
     exploreWatcher(),
-
-    onePostWatcher()
+    onePostWatcher(),
+    addCommentOnePostWatcher(),
+    changeLikePostWatcher()
     // addCommentFeedWatcher()
   ])
 }

+ 20 - 15
src/redux/reducers/post/postReducer.js

@@ -1,34 +1,39 @@
 import {actionOnePost} from '../../../actions'
 export const postReducer = (
     state = {},
-    { skip, type, newPosts = [], onePost, postsFeed, postsFeedCount },
+    { skip, type, newPosts = [], onePost,newResult, postsFeed, postsFeedCount },
   ) => {
     const types = {
-      'ONE-POST': () => {
+      'POST': () => {
         return {
           ...state,
           onePost,
         }
       },
-      'CLEAR-POST-ONE': () => {
+      'CLEAR_ONE_POST': () => {
         return {
           ...state,
           onePost: {},
         }
       },
-    }
+      'CHANGE_LIKE': () => {
+        return {
+          ...state,
+        onePost: ({...state?.onePost, likes: [...newResult] })
+        
+      }
+      },
+      'ADD_COMMENT': () => {
+        return {
+          ...state,
+        onePost: ({...state?.onePost, comments: [...newResult] })
+        
+      }
+      }
+  }
+  
     if (type in types) {
       return types[type]()
     }
     return state
-  }
-
-
-  //type
-  export const actionOnePostType = (onePost) => ({ type: 'ONE-POST', onePost })
-  export const actionClearPostsOne = () => ({ type: 'CLEAR-POST-ONE' })
- 
-   //one post
-export const actionFullOnePost = (_id) => ({
-  type:"ONE_POST", _id
-})
+  }

+ 93 - 35
src/redux/saga/index.js

@@ -16,6 +16,8 @@ import {
   actionAuthLogin,
   actionClearPromise,
   actionGetCommentsOnePost,
+  actionFindLikes,
+
   // actionOnePost
   } from '../../actions'
 import { history } from '../../helpers'
@@ -34,9 +36,9 @@ import { actionRemoveDataAboutMe } from '../reducers/profileData/profileReducer'
 import {actionExploreType,actionClearExplorePosts} from '../reducers/explore/exploreReducer'
 import { all, put,take, fork, takeEvery, takeLatest, takeLeading, select,call, join } from 'redux-saga/effects'; //
 import {actionPending,actionFulfilled,actionRejected,actionExplorePosts,actionExplorePostsCount} from '../../actions'
-import {actionOnePostType,} from '../reducers/post/postReducer'
-
-  //promise
+import { actionOnePostType, actionChangeLikeType } from '../../actions/types/postActionTypes'
+import {actionAddCommentType} from '../../actions/types/postActionTypes'
+  //promise 
  export function* promiseWorker(action){ //это типа actionPromise который thunk
     const {name, promise} = action
     yield put(actionPending(name)) //это как dispatch
@@ -173,7 +175,6 @@ export function* exploreWatcher() {
 //feed
 function* addCommentFeedWorker({ postId, newResult }) {
   yield call(promiseWorker,actionAddComment(postId, newResult))
-  console.log('ВВВВВВВВВВВВВВ')
   const { comments } = yield call(promiseWorker, actionGetCommentsOnePost(postId))
   console.log('commentsss', comments)
   if (comments)
@@ -223,41 +224,98 @@ function* onePostWorker({ _id }) {
 export function* onePostWatcher(){
 yield takeLeading("ONE_POST",onePostWorker)
 }
-// => async (dispatch) => {
-//   const onePost = await dispatch(actionOnePost(_id))
-//   if (onePost) {
-//     await dispatch(actionOnePostType(onePost))
-//     // await dispatch(actionClearDataUserType())
-//   }
 
-export const actionAddFullLikeFeed = (postId) => async (dispatch, getState) => {
-    await dispatch(actionAddLike(postId))
-    const {
-      promise: {
-        addLike: { status },
-      },
-    } = getState()
-    if (status === 'FULFILLED') {
-      const onePost = await dispatch(actionOnePost(postId))
-      if (onePost) await dispatch(actionAddLikePostInTape(postId))
-    }
+//comment
+
+function* addCommentOnePostWorker({ postId, text }) {
+  console.log('post id', postId)
+  console.log('comment', text)
+  const add= yield call(promiseWorker, actionAddComment(postId, text))
+  console.log('add', add)
+  const {
+    promise: {
+      addComment: { status },
+    },
+  } = yield select()
+  if (status === 'FULFILLED') {
+    yield call(promiseWorker, actionOnePost(postId))
+    const { comments } = yield call(promiseWorker, actionGetCommentsOnePost(postId))
+   console.log('add comments', comments)
+    if (comments)
+      yield put (actionAddCommentType(comments))
+  }
 }
+export function* addCommentOnePostWatcher(){
+  yield takeLeading("ONE_POST_COMMENT",addCommentOnePostWorker)
+  }
+  // await dispatch(actionOnePost(postId));
+// }}
+
+
+
+// export const actionAddFullLike = (postId) => async (dispatch, getState) => {
+//     await dispatch(actionAddLike(postId))
+//     const {
+//       promise: {
+//         addLike: { status },
+//       },
+//     } = getState()
+//     if (status === 'FULFILLED') {
+//       const onePost = await dispatch(actionOnePost(postId))
+//       if (onePost) await dispatch(actionAddLikePostInTape(postId))
+//     }
+// }
+
+export const actionChangeLike = (likeId, postId) =>
+({
+    type:"CHANGE_LIKE_POST", likeId,postId
+})
   
-export const actionDeleteFullLikeFeed = (likeId, postId) => async (
-    dispatch,
-    getState,
-  ) => {
-    await dispatch(actionDeleteLike(likeId, postId))
-    const {
-      promise: {
-        deleteLike: { status },
-      },
-    } = getState()
-    if (status === 'FULFILLED') {
-      const onePost = await dispatch(actionOnePost(postId))
-      if (onePost) await dispatch(actionDeleteLikePostInTape(likeId, postId))
-    }
+function* changeLikePostWorker({ likeId, postId }) {
+  console.log('likeId', likeId)
+  console.log('postId', postId)
+
+  const changeOneLike = () =>
+    likeId ? actionDeleteLike(likeId, postId) : actionAddLike(postId)
+
+  yield call(promiseWorker, changeOneLike())
+  const { likes } = yield call(promiseWorker, actionFindLikes(postId))
+  console.log('likes in worker', likes)
+
+  
+  if (likes) {
+  
+    yield call(promiseWorker, actionOnePost(postId))
+    yield put(actionChangeLikeType(likes))
   }
+  // const { likes } = yield call(promiseWorker, actionFindLikes(postId))
+  // console.log('likes', likes)
+  // if (likes)
+  // yield call(promiseWorker, actionOnePost(postId))
+}
+
+
+
+export function* changeLikePostWatcher() {
+  yield takeLeading("CHANGE_LIKE_POST", changeLikePostWorker)
+}
+
+
+// export const actionDeleteFullLikeFeed = (likeId, postId) => async (
+//     dispatch,
+//     getState,
+//   ) => {
+//     await dispatch(actionDeleteLike(likeId, postId))
+//     const {
+//       promise: {
+//         deleteLike: { status },
+//       },
+//     } = getState()
+//     if (status === 'FULFILLED') {
+//       const onePost = await dispatch(actionOnePost(postId))
+//       if (onePost) await dispatch(actionDeleteLikePostInTape(likeId, postId))
+//     }
+//   }
 
   //comment
 export const actionAddFullCommentFeed = (postId, newResult) => ({