SwapIt / app / profile / page.jsx
page.jsx
Raw
'use client'

import {useState, useEffect} from 'react';
import { useSession } from 'next-auth/react';
import { useRouter} from 'next/navigation';
import Profile from '@components/Profile';
import { toast } from 'react-toastify';


const ProfilePage = () => {
    const router = useRouter();
    const {data : session} = useSession();
    const [posts,setPosts] = useState([]);
    const handleEdit = (post) => {
        router.push(`/update-product?id=${post[0]}`)
    }
    const handleDelete = async (post) => {
        
        let hasConfirmed= window.confirm("Are you sure you want to delete?");
        if(hasConfirmed){
            try {
                await fetch(`/api/product/${post[0]}`,{
                    method : 'DELETE' 
                })
                const filteredPosts = posts.filter((p)=> p[0] !== post[0]);
                setPosts(filteredPosts)
            } catch (error) {
                console.log(error);
            }
        }
    }

    useEffect(() => {
        const fetchPosts = async () => {
            const res =await fetch(`/api/users/${session?.user?.id}/posts`);
            const data = await res.json();
            setPosts(data)
        }
        if(session?.user?.id){
            fetchPosts();
        }
    },[session])
    
  return (
    <Profile
        name= {session?.user?.name}
        desc = "Welcome, "
        data = {posts}
        handleEdit = {handleEdit}
        handleDelete = {handleDelete}
    >

    </Profile>
  )
}

export default ProfilePage