Home > Back-end >  Can I pass data fetched in getStaticProps to a component?
Can I pass data fetched in getStaticProps to a component?

Time:06-18

My getstaticProps:

export async function getStaticProps({ params }) {

  const mainMenuData = await fetch(
    `https://example.com/get/main-menu`
  ).then((res) => res.json());

  return {
    props: {
      mainMenuData,
    },
    revalidate: 60,
  };
}

Using the component:

<Header data={mainMenuData} />

My component:

export default function Header({ data }) {

  return (
    <>

      {data.main_menu}

    </>
  );
}

The data is an object, and I can access it so technically I know it's possible. However when I start mapping through the data I keep getting the error:

Hydration failed because the initial UI does not match what was rendered on the server

I'm new to Next and I'm not sure this method is correct.

Edit: Page component

import Head from "next/head";
import styles from "../styles/Home.module.css";
import Header from "../components/header";

export default function Page({ mainMenuData }) {

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
      <Header data={mainMenuData} />
      </main>
    </div>
  );
}

export async function getStaticProps({ params }) {

  const mainMenuData = await fetch(
    `https://example.com/get/main-menu`
  ).then((res) => res.json());

  return {
    props: {
      mainMenuData,
    },
    revalidate: 60,
  };
}

CodePudding user response:

This error might be happening due to not wrapping the data you are passing to Header properly in a JSX element. Try using a JSX element inside of Header like a div or ul if it's a list for example.

Also, avoid some JSX wrapping patterns such as, for example, a p tag wrapping up a div, section, etc. Next.js will most likely throw a similar error because of this.

  • Related