Home > front end >  Dynamic routes nextjs and firebase
Dynamic routes nextjs and firebase

Time:11-13

I am trying to add dynamic routes to NextJs and Firebase, so far when I click on the it redirects the user to the post that they clicked. I am just not able to get the post title and other information that is that post. Here is the code that I am using

export const getServerSideProps: GetServerSideProps = async () => {
  const doc = await getDocs(collection(db, "posts"));
  const data = doc;
  if (!data) return { notFound: true };
  return { props: { data } };   
};

const post = ({ data }: any) => {
  if (!data) {
    return "Loading...";
  }
  return <div>{data.title}</div>;
};

Updated

import { getDoc } from "@firebase/firestore/lite";


export const getServerSideProps = async (ctx: any) => {
  const doc = await getDoc(ctx.query.id)
  const data = doc.data()
  if (!data) return { notFound: true };
  return { props: { data } };
};

const Post = ({data}: any) => {
  if (!data) {
    return "Loading...";
  }

  return (
    <div>
      <p>Title: {data.title}</p>
    </div>
  );
}

export default Post;

When I tried this method it gives me this error.

TypeError: Cannot use 'in' operator to search for '_delegate' in f2i3YJCJki36FqNdyseX

f2i3YJCJki36FqNdyseX is the id of the document

CodePudding user response:

This is the way I used to solve the issue and fetch a single post

import { getDoc, doc } from "@firebase/firestore";
import { GetServerSideProps } from "next";
import { db } from "../../lib/firebase/firebase";


export const getServerSideProps: GetServerSideProps = async (ctx: any) => {
  const docRef = doc(db, "posts", ctx.query.id);
  const docSnap = await getDoc(docRef);
  const data = docSnap.data()
  console.log(data)
  if (!data) return { notFound: true };
  return { props: { data } };
};

const Post = ({data}: any) => {
  if (!data) {
    return "Loading...";
  }

  return (
    <div>
      <p>Title: {data.title}</p>
    </div>
  );
}

export default Post;
  • Related