chore(templates): add react cache to queryPostBySlug in website template (#7219)

This commit is contained in:
Paul
2024-07-18 14:20:05 -04:00
committed by GitHub
parent 442518dbc9
commit 2bd53a06eb
2 changed files with 8 additions and 17 deletions

View File

@@ -4,7 +4,7 @@ import { PayloadRedirects } from '@/components/PayloadRedirects'
import configPromise from '@payload-config'
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { draftMode, headers } from 'next/headers'
import React from 'react'
import React, { cache } from 'react'
import { homeStatic } from 'src/payload/seed/home-static'
import type { Page as PageType } from '../../../payload-types'
@@ -68,20 +68,16 @@ export async function generateMetadata({ params: { slug = 'home' } }): Promise<M
return generateMeta({ doc: page })
}
const queryPageBySlug = async ({ slug }: { slug: string }) => {
const queryPageBySlug = cache(async ({ slug }: { slug: string }) => {
const { isEnabled: draft } = draftMode()
const payload = await getPayloadHMR({ config: configPromise })
const authResult = draft ? await payload.auth({ headers: headers() }) : undefined
const user = authResult?.user
const result = await payload.find({
collection: 'pages',
draft,
limit: 1,
overrideAccess: false,
user,
overrideAccess: true,
where: {
slug: {
equals: slug,
@@ -90,4 +86,4 @@ const queryPageBySlug = async ({ slug }: { slug: string }) => {
})
return result.docs?.[0] || null
}
})

View File

@@ -5,8 +5,7 @@ import { PayloadRedirects } from '@/components/PayloadRedirects'
import configPromise from '@payload-config'
import { getPayloadHMR } from '@payloadcms/next/utilities'
import { draftMode, headers } from 'next/headers'
import { notFound } from 'next/navigation'
import React from 'react'
import React, { cache } from 'react'
import RichText from 'src/app/components/RichText'
import type { Post } from '../../../../payload-types'
@@ -66,20 +65,16 @@ export async function generateMetadata({ params: { slug } }): Promise<Metadata>
return generateMeta({ doc: post })
}
const queryPostBySlug = async ({ slug }: { slug: string }) => {
const queryPostBySlug = cache(async ({ slug }: { slug: string }) => {
const { isEnabled: draft } = draftMode()
const payload = await getPayloadHMR({ config: configPromise })
const authResult = draft ? await payload.auth({ headers: headers() }) : undefined
const user = authResult?.user
const result = await payload.find({
collection: 'posts',
draft,
limit: 1,
overrideAccess: false,
user,
overrideAccess: true,
where: {
slug: {
equals: slug,
@@ -88,4 +83,4 @@ const queryPostBySlug = async ({ slug }: { slug: string }) => {
})
return result.docs?.[0] || null
}
})