简体   繁体   中英

How can I generate a separate NextJS page for each FaunaDB Document?

How can I generate a different title on every page within a sub-directory?

My code throws no errors, but unfortunately the Title component renders every title-item on every page that it is supposed to, eg every app.com/title/<title> renders the same view ( a list of titles). I think that getStaticPaths is correctly parameterised, but I don't think that getStaticProps is.

export default function Title({ paper }) {

    // paper is just the entire dataset, and isn't split by id or author etc.

    return (
            <div>
                {paper.map(paper => (
                        <h1>{paper.data.title}</h1>
                ))}
            </div>
    )
}

export async function getStaticProps({ params }) {

    // ideally, results should be split down to e.g. `/api/getPapers/title`, but this didn't work

    const results = await fetch(`http://localhost:3000/api/getPapers/`).then(res => res.json());

    return {
        props: {
            paper: results
        }
    }
}

export async function getStaticPaths() {
    const papers = await fetch('http://localhost:3000/api/getPapers').then(res => res.json());

    const paths = papers.map(paper => {
        return {
            params: {
                authors: paper.data.title.toLowerCase().replace(/ /g, '-')
            }
        }
    })

    return {
        paths,
        fallback: false
    }
}

This is the getPapers API function.

const faunadb = require("faunadb");

// your secret hash
const secret = process.env.FAUNADB_SECRET_KEY;
const q = faunadb.query;
const client = new faunadb.Client({ secret });

module.exports = async (req, res) => {
  try {
    const dbs = await client.query(
      q.Map(
        // iterate each item in result
        q.Paginate(
          // make paginatable
          q.Match(
            // query index
            q.Index("all_research_papers") // specify source
          )
        ),
        (ref) => q.Get(ref) // lookup each result by its reference
      )
    );
    // ok
    res.status(200).json(dbs.data);
  } catch (e) {
    // something went wrong
    res.status(500).json({ error: e.message });
  }
};

You are returning authors in your Path object. You will need to make sure that your page file is named with authors included. For example:

app_directory
|- pages
  |- home.js
  |- title
    |- [authors].js

Perhaps where you say authors in your params object, you do mean title . In which case, rename the params object and page filename.

    const paths = papers.map(paper => {
        return {
            params: {
                title: paper.data.title.toLowerCase().replace(/ /g, '-')
            }
        }
    })
app_directory
|- pages
  |- home.js
  |- title
    |- [title].js

Here are the docs for getStaticPaths() . https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation

My attempts to render a separate page for each document were missing a dynamic API call. I was simply hoping to render dynamic pages with a single (batched-document) API call.

Here is a typical dynamic API route called [index.js] :

const faunadb = require('faunadb')

// your secret hash
const secret = process.env.FAUNADB_SECRET_KEY
const q = faunadb.query
const client = new faunadb.Client({ secret })

export default async (req, res) => {
  const {
    query: { index },
  } = req;

  try {
    const papers = await client.query(
      q.Get(q.Ref(q.Collection('<name of the collection>'), index))
    );
    res.status(200).json(papers.data);
  } catch (e) {
    res.status(500).json({ error: e.message });
  }
};


Once your data is being retrieved dynamically, you can set up a dynamic page route, eg [id].js , that fetches the data using useSWR .

const { data, error } = useSWR(`/api/getPapers/${id}`, fetcher);

This is an example fetcher function:

const fetcher = (url) => fetch(url).then((r) => r.json());

In my case, I could then retrieve any given field using the call {data.<field>} .

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