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({ resolver: yupResolver(validationSchema) }); const [response, setResponse] = useState(); 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 (

Mon Compte

Vous devez être authentifié pour voir cette page.
); } return (

Mon compte

Ma bio : {isUserProfile[0]?.bio}

{errors.bio?.message}

Email : {session.user.email}

{response &&

{response.message}

}
); }; export default Profil;