1
import Banner from "../components/Banner";
import Header from "../components/Header";
import PostCard from "../components/PostCard";
import { useContext } from "react";
import { MediumContext } from "../context/MediumContext";
import { db, auth, provider } from "../firebase";
import { collection, getDocs, setDoc, doc } from "firebase/firestore";

export default function Home({ staticPosts }) {
  const { postss, users } = useContext(MediumContext);
  const posts = staticPosts;
  // console.log(posts);
  // console.log(postss,"context")

  return (
    <>
      <Header />
      <Banner />
      <div className=" flex flex-col sm:grid-cols-2 lg:grid-cols-3">
        {!posts ? (
          <div>Loading</div>
        ) : (
          posts.map((post) => {
            return <PostCard post={post} key={post.id} />;
          })
        )}
      </div>
    </>
  );
}

export async function getStaticProps() {
  const querySnapshot = await getDocs(collection(db, "articles"));
  const staticPosts = querySnapshot.docs.map((doc) => {
    return {
      id: doc.id,
      data: {
        author: doc.data().author,
        body: doc.data().body,
        brief: doc.data().brief,
        category: doc.data().category,
        postLength: doc.data().postLength,
        title: doc.data().title,
        postedOn: doc.data().postedOn.toDate(),
        bannerImage: doc.data().bannerImage,
      },
    };
  });

  return {
    props: {
      staticPosts,
    },
  };
}

hey when i am trying this getStaticProps in nextjs it is showing me this error, previously i tried with useEffect() hook it worked fine , can anyone help he how to resolve this

Server Error Error: Error serializing .staticPosts[0].data.postedOn returned from getStaticProps in "/". Reason: object ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.

This error happened while generating the page. Any console logs will be displayed in the terminal window.

lucky
  • 31
  • 8

1 Answers1

0

hey i found this someWhere on google and tried , it works fine , making changes in return statement of getStaticPaths()

JSON.stringify() -- > this is used to convert object to string

JSON.parse() --> this is used to convert string to object

  return {
    props: {
      staticPosts: JSON.parse(JSON.stringify(staticPosts)),
    },
  };  
lucky
  • 31
  • 8
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 23 '22 at 23:06