如何避免在Next.js v13中两次获取相同的数据?

yjghlzjz  于 2023-06-22  发布在  其他
关注(0)|答案(2)|浏览(203)

我需要从数据库中查找一个条目,生成元数据并呈现实际的页面内容。
现在,我是这样做的:

export const generateMetadata = async ({
  params: { questionSlug },
}: Props): Promise<Metadata> => {
  const sql = await connectToPostgres();

  const question = await findQuestion(sql, questionSlug);

  if (!question) {
    return {};
  }

  return {
    alternates: {
      canonical: `https://ray.run/questions/${question.slug}`,
    },
    title: question.question,
  };
};

const Page = async ({ params: { questionSlug } }: Props) => {
  const sql = await connectToPostgres();

  const question = await findQuestion(sql, questionSlug);

  if (!question) {
    return notFound();
  }

  // ...
};

但这意味着我必须进行两次相同的数据库查询来呈现相同的页面。
有没有一种方法可以获取一次数据,然后在两种方法中使用它?

vlurs2pr

vlurs2pr1#

Next.js消除了generateMetadata的重复获取请求,但我不确定您的数据库连接。很好知道部分

rekjcdws

rekjcdws2#

试试这个:通过在最上面添加该高速缓存对象。

let cache ={};

export const generateMetadata = async ({
  params: { questionSlug },
}: Props): Promise<Metadata> => {
// This if statement return data from cache without send request to server.
if(cache) return cache;
  const sql = await connectToPostgres();

  const question = await findQuestion(sql, questionSlug);

  if (!question) {
    return {};
  }
  cache = question;
  return {
    alternates: {
      canonical: `https://ray.run/questions/${question.slug}`,
    },
    title: question.question,
  };
};

const Page = async ({ params: { questionSlug } }: Props) => {
  
  if (!cache) {
    await connectToPostgres();
    const question = await findQuestion(sql, questionSlug);
    if(!question) return notFound();
  }
  const response = cache;

  // ... use response variable as cache data.
};

相关问题