How to use dynamic head in Next js 13?
Asked Answered
H

1

5

before next js 13 we used to do dynamic head as an import. but in Next JS 13 they introduced the head.js class. this works when using a static page, but when loading a dynamic how can we change the title and desc in the head? i directly imported the next/head and then assign the data but it didn't change the head.

export default function DetailPage({ params: { itemid } }) {

const [datas, setDatas] = useState({});

  const getData = async () => {
    const docRef = doc(db, "items", itemid);
    const docSnap = await getDoc(docRef);
    setDatas(docSnap.data());
  };

  useEffect(() => {
    if (Object.keys(datas).length == 0) {
      getData();
    }
  }, [datas]);

return (

<>
<Head>
        <title>{datas.title}</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <meta
          name="keywords"
          content="some contents"
        />
        <meta
          name="description"
          content={datas.desc}
        />
      </Head>

  <section>...</section>

</>

)

}
Hysteroid answered 15/5, 2023 at 14:48 Comment(2)
When you print datas.title did you get the real value ?Repro
@dom1 yes it promptsHysteroid
J
7

I am guessing you are using the app directory, the Head component has been replaced by the generateMetadata API. Usage could use something like this inside your page:

import type { Metadata } from "next";

export function MyPage(): Promise<JSX.Element> {
  return <></>;
}

export async function generateMetadata(): Promise<Metadata> {
  const data = await getMyData();
  return {
    // return your metadata here
  };
}

You can find a full API reference and a method for static metadata inside the official docs.

Janenejanenna answered 15/5, 2023 at 19:58 Comment(7)
thats not working either. i've tried statically and dynamically but nothingHysteroid
I'm using firebase and i'm storing the fetched value inside useState. but the metadata only works in server sideHysteroid
it was my version, after upgrading it to the latest version it worksHysteroid
... so now you have to make the same request twice if you wanted that data in your page? -1Thorner
In code yes. But fetch requests are automatically deduped and reused. Or using Reacts new cache funtion will also dedupe not fetch based calls. Also, pretty rude to downvote a valid answer based on the lack of one ones knowledge.Janenejanenna
Poorly doucmented and not expressive enough. Next.js.Savino
@MarekMaurizio I am not affiliated with Next.js, so sadly nothing I can do about that. But I actually am quite fond of the documentation.Janenejanenna

© 2022 - 2024 — McMap. All rights reserved.