Skip to content

Commit

Permalink
Merge pull request #14 from ViniR07/develop
Browse files Browse the repository at this point in the history
Add Static Generation on HOC
  • Loading branch information
vinimrs authored May 10, 2022
2 parents bd23413 + 3e84b10 commit 34667ff
Show file tree
Hide file tree
Showing 12 changed files with 118 additions and 43 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

- [Typescript](https://www.typescriptlang.org)
- [NextJs](https://nextjs.org)
- [Recoil](https://recoiljs.org)

## Features :hammer:

Expand Down
13 changes: 7 additions & 6 deletions src/components/ManageProfileContainer/ProfileImages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as S from './styles';
import React from 'react';
import { convertImage } from '@utils';
import { IImageData, ISession } from '@types';
import { IImageData, IProfile } from '@types';
import { useSession } from '@hooks';

const ProfileImages: React.FC<{
setImageData: React.Dispatch<
Expand All @@ -10,21 +11,21 @@ const ProfileImages: React.FC<{
data: string;
}>
>;
session: ISession;
images: IImageData[];
}> = ({ setImageData, session, images }) => {
const filteredImages = (imgs: IImageData[]) => {
}> = ({ setImageData, images }) => {
const filteredImages = (imgs: IImageData[], profiles: IProfile[]) => {
return imgs.filter(img => {
const exists = session?.profiles.find(prof => {
const exists = profiles.find(prof => {
return prof.image._id === img._id;
});
return exists ? false : true;
});
};

const { session } = useSession();
return (
<S.ImageContainer>
{filteredImages(images).map(image => (
{filteredImages(images, session.profiles).map(image => (
<div
key={image._id}
id={image._id}
Expand Down
12 changes: 4 additions & 8 deletions src/components/ManageProfileContainer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ import { CustomButton, CustomTextField } from 'src/styles/GlobalComponents';
import { toSlug } from '@utils';
import { useRouter } from 'next/router';
import Link from 'next/link';
import { useAlert } from '@hooks';
import { useAlert, useSession } from '@hooks';
import ProfileImages from './ProfileImages';

const ManageProfileContainer: React.FC<{
editProfile: string;
session: ISession;
images: IImageData[];
}> = ({ editProfile, session, images }) => {
}> = ({ editProfile, images }) => {
const [preferences, setPreferences] = useState<string[]>([]);
const [profileName, setProfileName] = useState('');
const [imageData, setImageData] = useState({ id: '', data: '' });
const [loading, setLoading] = useState(false);

const { session } = useSession();
const alertActions = useAlert();
const router = useRouter();

Expand Down Expand Up @@ -126,11 +126,7 @@ const ManageProfileContainer: React.FC<{
<div className="profile__edit-session">
<div>
<h3>Escolha sua imagem</h3>
<ProfileImages
setImageData={setImageData}
session={session}
images={images}
/>
<ProfileImages setImageData={setImageData} images={images} />
</div>
<div className="inputs-wrapper">
<CustomTextField
Expand Down
20 changes: 19 additions & 1 deletion src/components/Register/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { MuiCustomInputProps, regExp } from '@constants';
import { useAlert } from '@hooks';
import { userService } from '@services';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, {
Expand All @@ -24,7 +26,9 @@ const Register: React.FC = () => {
const [confirmPassword, setConfirmPassword] = useState('');
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [loading, setLoading] = useState(false);
const router = useRouter();
const alertActions = useAlert();

const fieldValidation = (type: string, value: string) => {
const typeName = type === 'text' ? 'name' : type;
Expand All @@ -38,15 +42,21 @@ const Register: React.FC = () => {

const handleSubmit: FormEventHandler = e => {
e.preventDefault();
setLoading(true);
userService.registerUser(email, name, password).then(res => {
console.log(res);
if (res.status === 201) {
setConfirmPassword('');
setEmail('');
setName('');
setPassword('');

alertActions.success('Conta criada com sucesso!');
router.push('/email-confirmation');
} else {
alertActions.error(res.body.error);
}
setLoading(false);
});
};

Expand Down Expand Up @@ -200,7 +210,15 @@ const Register: React.FC = () => {
width="100%"
data-testid="Entrar"
>
Cadastrar
{loading && (
<Image
width="30px"
height="30px"
src="/loading-white.svg"
alt="Animação de carregamento"
/>
)}
{!loading && 'Cadastrar'}
</S.CustomButton>

<Link href="/login" passHref>
Expand Down
10 changes: 6 additions & 4 deletions src/components/SelectProfile/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import * as S from './styles';

const SelectProfile: React.FC<{ session: ISession }> = ({ session }) => {
const [profileHovered, setProfileHovered] = useState('');
const [profiles, setProfiles] = useState(session.profiles);
const { width } = useWindowDimensions();
const { setProfile } = useProfile();
const alertActions = useAlert();
Expand All @@ -23,7 +24,8 @@ const SelectProfile: React.FC<{ session: ISession }> = ({ session }) => {
if (res.ok) {
alertActions.success('Perfil deletado com sucesso');
}
router.push('/select-profile');
const currentProfiles = profiles.filter(p => p.slug !== prof.slug);
setProfiles(currentProfiles);
})
.catch(() => {
alertActions.error('Erro ao deletar o perfil');
Expand All @@ -39,7 +41,7 @@ const SelectProfile: React.FC<{ session: ISession }> = ({ session }) => {
<S.ProfileWrapper>
<h1>Quem está assistindo?</h1>
<div data-testid="profile-container">
{session.profiles?.length < 4 && (
{profiles.length < 4 && (
<div className="create-profile__container">
<div
onClick={() => {
Expand All @@ -59,8 +61,8 @@ const SelectProfile: React.FC<{ session: ISession }> = ({ session }) => {
</div>
)}

{session.profiles.length > 0 &&
session.profiles.map((prof, index) => (
{profiles.length > 0 &&
profiles.map((prof, index) => (
<div
className="profile-image__box"
title="Entre com o perfil"
Expand Down
1 change: 1 addition & 0 deletions src/components/SelectProfile/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export const ProfileWrapper = styled.div`
}
& > .profile-image__box {
margin: 12px 0;
border-color: var(--white);
h2 {
color: var(--white);
Expand Down
17 changes: 5 additions & 12 deletions src/pages/manage-profile.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import { IImageData, ISession } from '@types';
import { useRouter } from 'next/router';
import { withSession } from '../services/auth/session';
import { withSessionHOC } from '../services/auth/session';
import { HttpClient } from '../infra/HttpClient/HttpClient';

import ManageProfileContainer from '../components/ManageProfileContainer';
Expand All @@ -13,7 +13,6 @@ interface CreateManageProfilesProps {
}

const ManageProfilesPage: React.FC<CreateManageProfilesProps> = ({
session,
images,
}) => {
const [editProfile, setEditProfile] = useState('');
Expand All @@ -30,26 +29,20 @@ const ManageProfilesPage: React.FC<CreateManageProfilesProps> = ({

return (
<Layout title="Netflix - Manage Profile">
<ManageProfileContainer
session={session}
images={images}
editProfile={editProfile}
/>
<ManageProfileContainer images={images} editProfile={editProfile} />
</Layout>
);
};

export const getServerSideProps = withSession(async ctx => {
export async function getStaticProps() {
const res = await HttpClient(`${process.env.NEXT_PUBLIC_BACKEND_URL}/image`, {
method: 'GET',
});

return {
props: {
images: res.body,
session: ctx.req.session,
},
};
});
}

export default ManageProfilesPage;
export default withSessionHOC(ManageProfilesPage);
12 changes: 2 additions & 10 deletions src/pages/select-profile.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { withSession } from '../services/auth/session';
import { withSessionHOC } from '../services/auth/session';
import { ISession } from '@types';
import FirstHeader from '../components/FirstHeader';
import Layout from 'src/components/Layout';
Expand All @@ -16,12 +16,4 @@ const SelectProfilePage: React.FC<{
);
};

export const getServerSideProps = withSession(async ctx => {
return {
props: {
session: ctx.req.session,
},
};
});

export default SelectProfilePage;
export default withSessionHOC(SelectProfilePage);
53 changes: 52 additions & 1 deletion src/services/auth/session.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { useRouter } from 'next/router';
import React from 'react';
import Loading from 'src/components/Loading';
import { authService } from './authService';
import { useSession } from '@hooks';

export function withSession(funcao: (ctx) => any) {
return async ctx => {
Expand All @@ -16,9 +20,56 @@ export function withSession(funcao: (ctx) => any) {
return {
redirect: {
permanent: false,
destination: '/login/',
destination: '/login',
},
};
}
};
}

// Static pages
export function useStaticSession() {
const { session, setSession } = useSession();
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);

React.useEffect(() => {
authService
.getSession()
.then(session => {
setSession(session);
})
.catch(err => setError(err))
.finally(() => {
setLoading(false);
});
}, []);

return {
data: {
session,
},
error,
loading,
};
}

// Componente de Ordem Superior Static-pages
export function withSessionHOC(Component: React.ComponentType) {
return function Wrapper(props) {
const router = useRouter();
const session = useStaticSession();

if (session.loading) return <Loading />;

if (!session.loading && session.error) {
router.push('/login');
}

const modifiedProps = {
...props,
session: session.data.session,
};
return <Component {...modifiedProps} />;
};
}
12 changes: 11 additions & 1 deletion src/state/atoms/user.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IProfile } from '@types';
import { IImageData, IProfile, ISession } from '@types';
import { atom } from 'recoil';

const localStorage = typeof window !== 'undefined' ? window.localStorage : null;
Expand All @@ -24,3 +24,13 @@ export const profileAtom = atom<IProfile>({
default: localStorage ? JSON.parse(localStorage.getItem('usuario')) : {},
effects: [localStorageEffect('usuario')],
});

export const sessionAtom = atom<ISession>({
key: 'sessionAtom',
default: {} as ISession,
});

export const imagesAtom = atom<IImageData[]>({
key: 'imagesAtom',
default: [{}] as IImageData[],
});
1 change: 1 addition & 0 deletions src/state/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './useHeroData';
export * from './useHomeMovieList';
export * from './useProfile';
export * from './useWindowDimensions';
export * from './useSession';
9 changes: 9 additions & 0 deletions src/state/hooks/useSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ISession } from '@types';
import { useRecoilState } from 'recoil';
import { sessionAtom } from '../atoms';

export const useSession = () => {
const [session, setSession] = useRecoilState<ISession>(sessionAtom);

return { session, setSession };
};

1 comment on commit 34667ff

@vercel
Copy link

@vercel vercel bot commented on 34667ff May 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

netflix-clone – ./

vinflix.vercel.app
netflix-clone-git-master-vinir07.vercel.app
netflix-clone-vinir07.vercel.app

Please sign in to comment.