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(); const [polls, setPolls] = useState([]); const [totalVotes, setTotalVotes] = useState(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 ( {isPollsLoading ? : (polls.length > 0 && )} ); }; export default ProfilePage;