You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
The_Tip_Top/pages/profile.tsx

172 lines
4.2 KiB

import React, { useState } from "react";
import { GetServerSideProps } from "next";
import Layout from "../components/Layout";
import { useSession, getSession } from "next-auth/react";
import prisma from '../lib/prisma'
import Router from "next/router";
import { ProfileProps } from "../types/profile";
import { Resolver, SubmitHandler } from "react-hook-form";
//https://www.bezkoder.com/react-hook-form-typescript/
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';
type UserSubmitForm = {
bio: string;
};
type Profil = {
isUserProfile: any;
}
interface ResponseData {
result: string;
message: string
}
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
const session = await getSession({ req });
//pas de session ? on ne retourne un code erreur
//voir pour rediriger vers la page de connection
//ou afficher pop up "vous n'est pas connecter"
if (!session) {
res.statusCode = 403;
return { props: { profile: null } };
}
// si session ? on récupére le profil de l'utilisateur si il existe
if (session) {
const isUserProfile = await prisma.profile.findMany({
where: {
user: { email: session.user.email },
}
})
console.log('profil utilisateur ?', isUserProfile);
// il n'existe pas ? on le crée
if (isUserProfile.length <= 0) {
const newProfil = await prisma.profile.create({
data: {
bio: "",
user: {
connect: { email: session.user.email },
},
},
});
console.log('newProfil', newProfil);
}
// on renvoi le profil
return { props: { isUserProfile } };
}
};
const Profil = ({ isUserProfile }: Profil) => {
const validationSchema = Yup.object().shape({
bio: Yup.string().trim().required("ce champ ne peux etre vide..."),
});
const {
register,
handleSubmit,
reset,
formState: { errors }
} = useForm<UserSubmitForm>({
resolver: yupResolver(validationSchema)
});
const [response, setResponse] = useState<ResponseData | undefined>();
const { data: session } = useSession();
React.useEffect(() => {
console.log('user profil props', isUserProfile)
}, [])
const onSubmit = async (data: UserSubmitForm) => {
console.log(data);
try {
const body = { bioValue: data.bio };
await fetch(`/api/profile`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
.then((res) => res.json())
.then((data) => {
setResponse(data);
console.log('response', data);
})
await Router.push("/profile");
} catch (error) {
console.error(error);
}
};
if (!session) {
return (
<Layout>
<h1>Mon Compte</h1>
<div>Vous devez être authentifié pour voir cette page.</div>
</Layout>
);
}
return (
<Layout>
<div className="page">
<h1>Mon compte</h1>
<main>
<div className="register-form">
<p>Ma bio : {isUserProfile[0]?.bio}</p>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-group">
<label>Ma bio :</label>
<input
placeholder="Ma bio..."
defaultValue={isUserProfile[0]?.bio}
type="text"
{...register('bio')}
className={`form-control ${errors.bio ? 'is-invalid' : ''}`}
/>
<div className="invalid-feedback">{errors.bio?.message}</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Valider les changements
</button>
<button
type="button"
onClick={() => reset()}
className="btn btn-warning float-right"
>
Reset
</button>
</div>
</form>
</div>
<p>Email : {session.user.email}</p>
{response && <p>{response.message}</p>}
</main>
</div>
</Layout>
);
};
export default Profil;