Skip to content

Commit

Permalink
Fix bugs, state management && backend api fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
n1klaus committed May 14, 2023
1 parent 0c1885d commit 1e4f640
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 103 deletions.
2 changes: 1 addition & 1 deletion frontend/src/components/Recommendation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function Recommendation({ tags }: { tags: Array<string> }) {
setVideos(res.data);
};
fetchVideos();
}, [tags]);
}, []);

return (
<Container>
Expand Down
11 changes: 6 additions & 5 deletions frontend/src/pages/history.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,19 @@ const Container = styled.div`
`;

function HistoryPage() {
const store = useStore();
const user = store.authUser;
const user = useStore((state) => state.authUser);
const [videos, setVideos] = useState([]);

useEffect(() => {
const SERVER_ENDPOINT = import.meta.env.VITE_BACKEND_ENDPOINT;
const fetchVideos = async () => {
const res = await axios.get(
await axios.get(
`${SERVER_ENDPOINT}/users/${user?._id}/history`,
{ withCredentials: true },
);
setVideos(res.data);
)
.then((data) => {
setVideos(data.data);
});
};
fetchVideos();
}, []);
Expand Down
31 changes: 16 additions & 15 deletions frontend/src/pages/profile.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { toast } from 'react-toastify';
// import styled from 'styled-components';
import axios from 'axios';
import useStore from '../store';
import { IUser, IChannel } from '../utils/types';
import { IChannel } from '../utils/types';

// const Button = styled.button`
// border-radius: 3px;
Expand All @@ -25,22 +25,23 @@ function ProfilePage() {
const fetchUser = async () => {
try {
store.setRequestLoading(true);
const response = await axios.get(`${SERVER_ENDPOINT}/users/me`, {
await axios.get(`${SERVER_ENDPOINT}/users/me`, {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
});
if (response.status !== 200) {
throw new Error(response.statusText);
}

const user = response.data.user as IUser;
// console.log(user);
})
.then((data) => {
if (data.status !== 200) {
throw new Error(data.statusText);
}
const { user } = data.data.data as any;
store.setAuthUser(user);
store.setCurrentChannel(user.channels[0] as unknown as IChannel);
return user;
});
store.setRequestLoading(false);

store.setAuthUser(user);
store.setCurrentChannel(user.channels[0] as unknown as IChannel);
return;
} catch (error: any) {
store.setRequestLoading(false);
if (error.error) {
Expand Down Expand Up @@ -115,7 +116,7 @@ function ProfilePage() {
fetchUser();
}, []);

const user = store.authUser;
const user = useStore((state) => state.authUser);

return (
<section className="bg-ct-blue-600 min-h-screen pt-20">
Expand Down Expand Up @@ -149,7 +150,7 @@ function ProfilePage() {
<p className="mb-3">
Subscriptions:
{' '}
{user.subscriptions.length}
{user?.subscriptions.length}
</p>
<p className="mb-3">
Channels:
Expand All @@ -159,7 +160,7 @@ function ProfilePage() {
Default Channel:
{' '}
{user.channels.length > 0
? (user.channels[0] as unknown as IUser)._id
? (user.channels[0] as unknown as IChannel)._id
: ''}
</p>
<p className="mb-3">
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/pages/register.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function RegisterPage() {
const navigate = useNavigate();
const location = useLocation();
const store = useStore();
const from = ((location.state as any)?.from.pathname as string) || '/profile';
const from = ((location.state as any)?.from?.pathname as string) || '/profile';

const registerUser = async (data: RegisterInput) => {
try {
Expand All @@ -46,7 +46,8 @@ function RegisterPage() {
},
},
);
if (response.status !== 200) {
console.log(response.status);
if (response.status !== 201) {
throw new Error(response.statusText);
}

Expand Down
11 changes: 6 additions & 5 deletions frontend/src/pages/subscriptions.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,19 @@ const Container = styled.div`
`;

function SubscriptionsPage() {
const store = useStore();
const user = store.authUser;
const user = useStore((state) => state.authUser);
const [channels, setChannels] = useState([]);

useEffect(() => {
const SERVER_ENDPOINT = import.meta.env.VITE_BACKEND_ENDPOINT;
const fetchVideos = async () => {
const res = await axios.get(
await axios.get(
`${SERVER_ENDPOINT}/users/${user?._id}/subscriptions`,
{ withCredentials: true },
);
setChannels(res.data);
)
.then((data) => {
setChannels(data.data);
});
};
fetchVideos();
}, []);
Expand Down
130 changes: 55 additions & 75 deletions frontend/src/pages/video.page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect } from 'react';
import styled from 'styled-components';
import ThumbUpOutlinedIcon from '@mui/icons-material/ThumbUpOutlined';
import ThumbDownOffAltOutlinedIcon from '@mui/icons-material/ThumbDownOffAltOutlined';
Expand All @@ -11,7 +11,6 @@ import axios from 'axios';
import { format } from 'timeago.js';
import { toast } from 'react-toastify';
import Recommendation from '../components/Recommendation';
import { IChannel, IUser, IVideo } from '../utils/types';
import useStore from '../store';
import Comments from '../components/Comments';

Expand Down Expand Up @@ -123,71 +122,33 @@ function VideoPage() {
const store = useStore();
const navigate = useNavigate();
const { id } = useParams();
const [currentChannel, setChannel] = useState<IChannel>({
_id: '',
name: '',
description: '',
imgUrl: '',
views: 0,
tags: [],
likes: [],
dislikes: [],
videos: [],
subscribers: 0,
isPublic: false,
createdAt: '',
});
const [currentUser, setUser] = useState<IUser>({
_id: '',
username: '',
email: '',
avatar: '',
subscriptions: [],
history: [],
channels: [],
fromGoogle: false,
});
const [currentVideo, setVideo] = useState<IVideo>({
_id: '',
userId: '',
channelId: '',
title: '',
description: '',
imgUrl: '',
videoUrl: '',
views: 0,
tags: [],
likes: [],
dislikes: [],
isPublic: false,
createdAt: '',
});

const currentChannel = useStore((state) => state.currentChannel);
const currentVideo = useStore((state) => state.currentVideo);
const authUser = useStore((state) => state.authUser);
useEffect(() => {
const fetchData = async () => {
try {
const videoRes = await axios.get(
`${SERVER_ENDPOINT}/videos/${id}/view`,
);
const channelRes = await axios.get(
`${SERVER_ENDPOINT}/channels/${videoRes.data.channelId}/view`,
);
const userRes = await axios.get(
`${SERVER_ENDPOINT}/users/${channelRes.data.userId}`,
{ withCredentials: true },
);
setUser(userRes.data);
setChannel(channelRes.data);
setVideo(videoRes.data);
store.setAuthUser(userRes.data);
store.setCurrentVideo(videoRes.data);
store.setCurrentChannel(channelRes.data);
)
.then((data: any) => {
store.setCurrentVideo(data.data);
return data.data;
});

await axios.get(
`${SERVER_ENDPOINT}/channels/${videoRes.channelId}/view`,
)
.then((data: any) => {
store.setCurrentChannel(data.data);
return data.data;
});
} catch (err) {
console.error(err);
}
};
fetchData();
}, [id]);
}, []);

const handleLike = async () => {
try {
Expand Down Expand Up @@ -244,17 +205,20 @@ function VideoPage() {

const handleSub = async () => {
try {
if (currentUser.subscriptions.includes(currentChannel?._id)) {
if (!currentChannel || !currentChannel._id) {
throw new Error('Channel not found!');
}
if (authUser?.subscriptions.includes(currentChannel._id)) {
await axios.put(
`${SERVER_ENDPOINT}/users/unsubscribe/${currentChannel?._id}`,
`${SERVER_ENDPOINT}/users/unsubscribe/${currentChannel._id}`,
{},
{
withCredentials: true,
},
);
} else {
await axios.put(
`${SERVER_ENDPOINT}/users/subscribe/${currentChannel?._id}`,
`${SERVER_ENDPOINT}/users/subscribe/${currentChannel._id}`,
{},
{
withCredentials: true,
Expand Down Expand Up @@ -282,6 +246,15 @@ function VideoPage() {
const handlePlay = async () => {
try {
await axios.put(`${SERVER_ENDPOINT}/videos/${id}/view`);
if (authUser) {
await axios.put(
`${SERVER_ENDPOINT}/users/history/${id}`,
{},
{
withCredentials: true,
},
);
}
} catch (error: any) {
console.log(error?.message);
const resMessage = (error.response
Expand Down Expand Up @@ -327,7 +300,7 @@ function VideoPage() {

// TODO share functionality
const handleShare = async () => {};
console.log(store.authUser);
// console.log(store.authUser);
return (
<Container>
<Content>
Expand All @@ -338,26 +311,26 @@ function VideoPage() {
controls
/>
</VideoWrapper>
<Title>{currentVideo.title}</Title>
<Title>{currentVideo?.title}</Title>
<Details>
<Info>
{currentVideo.views}
{currentVideo?.views}
{' '}
views •
{format(currentVideo.createdAt)}
{format(String(currentVideo?.createdAt))}
</Info>
<Buttons>
<Button onClick={handleLike}>
{currentVideo.likes?.includes(currentUser?._id) ? (
{currentVideo?.likes?.includes(String(authUser?._id)) ? (
<ThumbUpIcon />
) : (
<ThumbUpOutlinedIcon />
)}
{' '}
{currentVideo.likes?.length}
{currentVideo?.likes?.length}
</Button>
<Button onClick={handleDislike}>
{currentVideo.dislikes?.includes(currentUser?._id) ? (
{currentVideo?.dislikes?.includes(String(authUser?._id)) ? (
<ThumbDownIcon />
) : (
<ThumbDownOffAltOutlinedIcon />
Expand All @@ -380,29 +353,36 @@ function VideoPage() {
<Hr />
<Channel>
<ChannelInfo>
<Image src={currentChannel.imgUrl} />
<Image src={currentChannel?.imgUrl} />
<ChannelDetail>
<ChannelName>{currentChannel.name}</ChannelName>
<ChannelName>{currentChannel?.name}</ChannelName>
<ChannelCounter>
{currentChannel.subscribers > 0
? currentChannel.subscribers
: 0}
{
currentChannel?.subscribers
&& currentChannel?.subscribers > 0
? currentChannel?.subscribers
: 0
}
{' '}
subscribers
</ChannelCounter>
<Description>{currentVideo.description}</Description>
<Description>{currentVideo?.description}</Description>
</ChannelDetail>
</ChannelInfo>
<Subscribe onClick={handleSub}>
{currentUser.subscriptions?.includes(currentChannel._id)
{authUser?.subscriptions?.includes(String(currentChannel?._id))
? 'UNSUBSCRIBE'
: 'SUBSCRIBE'}
</Subscribe>
</Channel>
<Hr />
<Comments videoId={id} />
</Content>
<Recommendation tags={currentVideo.tags} />
{
currentVideo?.tags
? <Recommendation tags={Array.from(currentVideo?.tags)} />
: null
}
</Container>
);
}
Expand Down
1 change: 1 addition & 0 deletions frontend/src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface IUser {

export interface IChannel {
_id: string;
userId: string;
name: string;
description: string;
imgUrl: string;
Expand Down

0 comments on commit 1e4f640

Please sign in to comment.