aboutsummaryrefslogtreecommitdiff
path: root/src/pages/ProfilePage/ProfilePage.tsx
blob: ba4db7dfb2bf7228a96d5af69332d892756cef45 (plain)
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
import React, { useState, useEffect } from 'react';
import { User, Poll } from 'which-types';
import { Container } from '@material-ui/core';

import ProfileInfo from './ProfileInfo';
import Feed from '../../components/Feed/Feed';
import { get } from '../../requests';
import { useAuth } from '../../hooks/useAuth';
import { useNavigate } from '../../hooks/useNavigate';


const ProfilePage: React.FC = () => {
  const [userInfo, setUserInfo] = useState<User>();
  const [polls, setPolls] = useState<Poll[]>([]);
  const [totalVotes, setTotalVotes] = useState<number>(0);
  const { page, navigate } = useNavigate();
  const { user } = useAuth();
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const id = page?.id || user?._id;
    setIsLoading(true);
    if (id) {
      get(`/users/${id}`).then(response => {
        setUserInfo(response.data);
      });
      get(`/profiles/${id}`).then(response => {
        setPolls([]);
        setPolls(response.data);
        setTotalVotes(response.data.reduce(
          (total: number, current: Poll) => {
            const { left, right } = current.contents;
            return total + left.votes + right.votes;
          }, 0
        ));
        setIsLoading(false);
      });
    } else navigate('auth');
  }, [navigate, page, user]);

  return (
    <Container maxWidth="sm" disableGutters>
      <ProfileInfo
        userInfo={userInfo}
        setUserInfo={setUserInfo}
        savedPolls={polls.length}
        totalVotes={totalVotes}
        loading={isLoading}
      />
      <Feed polls={[...polls]} />
    </Container>
  );
};

export default ProfilePage;