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

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

import Form from '@components/Form';
import { toast } from "react-toastify";

const Sell= () => {
  const router = useRouter();
  const {data : session } = useSession();
  const [Submitting, setSubmitting] = useState(false);
  // const [isInitialRender, setIsInitialRender] = useState(true);
  // const [isLoggedIn, setLogin] = useState(false);

  const [Post, setPost] = useState({
      User_ID: '',
      NOP: '',
      type: '', 
      image : '',
      desc: '',
      price: '',
  });

  
  // useEffect(()=>{
  //   console.log("1st UseEffect");
  //   if(session) {
  //     console.log(session, "\t")
  //     setLogin(true)
  //     console.log("Yess\n")
  //   }
  // },[session]);

  // useEffect(() => {
  //   if (!isInitialRender) {
  //     if (!isLoggedIn) router.push('/');
  //   } else {
  //     setIsInitialRender(false);
  //   }
  // }, [isLoggedIn, isInitialRender, router]);

  const CreateProduct = async (e) => {
    e.preventDefault();
    if(Post.image=='') return toast.error("Atleast one image is required!")
    setSubmitting(true);
    try{
      const res = await fetch('/api/product/new',
        {
          method: 'POST',
          body: JSON.stringify({
            User_Id: session?.user.id,
            NOP: Post.NOP,
            type: Post.type,
            image: Post.image,
            desc: Post.desc,
            price: Post.price,
          })
        });
      if(res.ok){
        router.push('/')
      }

    }catch(error){
      console.log(error);
    }finally{
      setSubmitting(false);
    }
  } 

  return (
    <Form 
        type = 'New'
        Post = {Post}
        setPost = {setPost}
        Submitting ={Submitting}
        handleSubmit = {CreateProduct}
    />
  )
}

export default Sell;