Next.js Discord

Discord Forum

query article on page -> then set metadata on page? 🤔

Answered
piscopancer posted this in #help-forum
Open in Discord
export default async function ArticlePage({ params }: TNextPage<'slug'>) {
    const article = await queryArticle(params.slug) // article: TArticle | undefined

    if (!article)
        return (
            <div>
                <p>No article found. Check the slug</p>
                <pre>{params.slug}</pre>
            </div>
        )

    return <div>{article.title}</div>
}


when an articles is found, I want to set metadata to page, specifically the title of the page to be the article's, if it wasn't found, then I would set the page title to "ooops...". How can it be done?

is it the only way? 👇
export async function generateMetadata({ params }: TNextPage<'slug'>) {
    const article = await queryArticle(params.slug)
  return {
    title: article?.title ?? 'ooops...',
  }
}

export default async function ArticlePage({ params }: TNextPage<'slug'>) {
    const article = await queryArticle(params.slug)

    if (!article)
        return (
            <div>
                <p>Хм, такой статьи я не писал. Проверьте адрес</p>
                <pre>{params.slug}</pre>
            </div>
        )

    return <div>{article.title}</div>
}

in the above sane code, I am repeating the code. disgusting 💔
Answered by joulev
it's the only way yes and that's how it should work. use [request memoisation](https://nextjs.org/docs/app/building-your-application/caching#request-memoization) to ensure only one request is actually made
View full answer

4 Replies

Answer
use cache() if you don't use fetch() for that function
then it will be memoised yeah