query article on page -> then set metadata on page? 🤔
Answered
piscopancer posted this in #help-forum
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
4 Replies
@piscopancer tsx
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? 👇
tsx
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 💔
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
Answer
@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
hmmm yeah understand, did not know queries could also be cached. 💖
use cache() if you don't use fetch() for that function
then it will be memoised yeah