File size: 2,477 Bytes
f5071ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Box } from '@chakra-ui/react';
import React from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/auth';
import {
   calcTotalDiscussion,
   calculateReaction,
} from '../../helper/calculateTotal';
import { PrimaryBtn } from '../../utils/Buttons';
import PostItem from '../post/PostItem';
import NoDataMessage from './NoDataMessage';

const Posts = () => {
   const user = useAuth();
   const userId = user.userId;
   const navigate = useNavigate();

   const {
      transformedData,
      transformedDataLoading: loading,
      transformedDataErr: err,
   } = useSelector((state) => state.transformedData);

   let publishedPosts = null;
   if (transformedData && !loading && !err) {
      publishedPosts = transformedData
         .filter((postData) => postData.userId === userId && !postData.draft)
         .sort((a, b) => b.createdAt - a.createdAt);
   }

   if (publishedPosts.length === 0 && !loading && !err) {
      return (
         <NoDataMessage
            title={`This is where you can manage your posts, but you haven't written anything yet.`}
         >
            <PrimaryBtn
               bg='light.primary'
               m='1rem 0 0 0'
               onClick={() => navigate('/create-post')}
            >
               Write your first post now
            </PrimaryBtn>
         </NoDataMessage>
      );
   }

   return (
      <Box>
         {publishedPosts &&
            publishedPosts.map((postData) => (
               <PostItem
                  key={postData.id}
                  name={postData.name}
                  username={postData.username}
                  profile={postData.profile}
                  id={postData.id}
                  createdAt={postData.createdAt}
                  title={postData.title}
                  tags={postData.tags}
                  readTime={postData.readTime}
                  isUpdated={postData?.updated}
                  fromDashboard={true}
                  userId={postData.userId}
                  currentUserId={user.userId} // authenticated userId
                  totalDiscussion={calcTotalDiscussion(postData.comments)}
                  totalReaction={calculateReaction(
                     postData.heart,
                     postData.unicorn,
                     postData.saved
                  )}
               />
            ))}
      </Box>
   );
};

export default Posts;