aboutsummaryrefslogtreecommitdiff
path: root/src/pages/ProfilePage/ProfilePage.tsx
blob: ae94b9f70e70daa05dd595bd6fcaad4644298b4d (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import React, { useState, useEffect } from 'react';
import { useHistory, useParams } from 'react-router-dom';
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';


const ProfilePage: React.FC = () => {
  const [userInfo, setUserInfo] = useState<User>();
  const [polls, setPolls] = useState<Poll[]>([]);
  const [totalVotes, setTotalVotes] = useState<number>(0);
  const [isInfoLoading, setIsInfoLoading] = useState(false);
  const [isPollsLoading, setIsPollsLoading] = useState(false);
  const history = useHistory();
  const { username } = useParams();
  const { user } = useAuth();

  useEffect(() => {
    setIsInfoLoading(true);

    const redirect = () => {
      if (user) history.push(`/profile/${user.username}`);
      else history.push('/login');
    };

    if (username) {
      get(`/users?username=${username}`).then(response => {
        if (!response.data.length) redirect(); // TODO: handle this case
        setUserInfo(response.data[0]);
        setIsInfoLoading(false);
      }).catch(() => redirect());
    } else redirect();
  }, [username, user, history]);


  useEffect(() => {
    if (userInfo?._id) {
      setIsPollsLoading(true);

      get(`/profiles/${userInfo._id}`).then(response => {
        setIsPollsLoading(false);
        setPolls([]);
        setPolls(response.data);
        setTotalVotes(response.data.reduce(
          (total: number, current: Poll) => {
            const { left, right } = current.contents;
            return total + left.votes + right.votes;
          }, 0
        ));
      });
    }
  }, [userInfo]);

  return (
    <Container maxWidth="sm" disableGutters>
      <ProfileInfo
        userInfo={userInfo}
        setUserInfo={setUserInfo}
        savedPolls={polls.length}
        totalVotes={totalVotes}
        isLoading={isInfoLoading}
      />
      {isPollsLoading ? <Feed polls={[]} /> : (polls.length > 0 && <Feed polls={polls} />)}
    </Container>
  );
};

export default ProfilePage;