简体   繁体   中英

Next.js dynamic routes with Firestore collection

I'm looking for a way to have a dynamic route that displays for every document in a Firestore collection using Server-side Rendering.

For example, a document called foo would exist at test.com/foo under the [doc] page component. Any time a document is added, it should be able to be accessed through its respective URL.

I've tried this method but I haven't been able to get it to work. I've also tried implementing getServerSideProps but have not had much success, any pointers would be appreciated.

Code from the method above as follows:

under pages/api/[doc].js

export default (req, res) => {
  db.collection("docs")
    .doc(req.query.name)
    .get()
    .then((doc) => {
      res.json(doc.data());
    })
    .catch((error) => {
      res.json({ error });
    });
};

under pages/[shoal].jsx

import { useRouter } from "next/router";
import useSWR from "swr";

const fetcher = async (...args) => {
  const res = await fetch(...args);

  return res.json();
};

function Doc() {
  const router = useRouter();
  const { name } = router.query;
  const { data } = useSWR(`/api/${name}`, fetcher);

  if (!data) {
    return "Loading...";
  }

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

export default Doc;

You can try using getServerSideProps :

export const getServerSideProps = async (ctx) => {
  const doc = await db.collection("docs").doc(ctx.query.id).get()
  const data = doc.data()
  if (!data) return { notFound: true };
  return { props: { data } };
};

function Doc({data}) {
  const router = useRouter();
  const { name } = router.query;

  if (!data) {
    return "Loading...";
  }

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

export default Doc;

Simple solution.

const { data } = useSWR(api ? '/api/${name}' : null, fetcher);

Conditionally fetch the data if your variable is defined, if not, don't pass a URL string, better yet; you can conditionally consider the fetcher for usage also.

const { data } = useSWR(name ? '/api/${name}' : null, name ? fetcher : null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM