1

I have a custom _app.js which looks like this:

function MyApp({ Component, pageProps }) {
  const Layout = Component.layoutProps?.Layout || React.Fragment
  const layoutProps = Component.layoutProps?.Layout
    ? { layoutProps: Component.layoutProps }
    : {}
  const meta = Component.layoutProps?.meta || {}
  const description =
    meta.metaDescription || meta.description || 'Meta Description'
  const store = useStore(pageProps.initialReduxState)

  return (
    <QueryClientProvider client={queryClient}>
      <Provider session={pageProps.session}>
        <Title suffix="My Dynamic Site">{meta.metaTitle || meta.title}</Title>
        <Description>{description}</Description>
        <Meta />
        <ReduxProvider store={store}>
          <PersistGate persistor={store.__PERSISTOR} loading={null}>
            <CartBox />
            <Layout {...layoutProps}>
              <Component {...pageProps} />
            </Layout>
          </PersistGate>
        </ReduxProvider>
        <ReactQueryDevtools initialIsOpen={false} />
      </Provider>
    </QueryClientProvider>
  )
}

MyApp.getInitialProps = async (appContext) => {
  // calls page's `getInitialProps` and fills `appProps.pageProps`
  const appProps = await App.getInitialProps(appContext);

  return { ...appProps }
}

export default MyApp

Now, I would like to fetch data using ssg/ssr data fetching method to help SEO team for my page components. But, it seems any of the methods aren't working as expected, none of them actually passing props to the page component. Here's my page component.

const HomePage = ({ title, stars }) => {
  console.log(title, stars);  // undefined, undefined
  return (
    <div>
      <Header title={title} />
      <GhStars stars={stars} />
      <Footer />
    </div>
  )
}

export const getStaticProps = async () => {
  return {
    props: {
      title: "My Dynamic Title From getStaticProps"
    }
  }
}

// I tried both getInitialProps & getStaticProps independently.
HomePage.getInitialProps = async (ctx) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default HomePage

I might be missing something for sure, which I failed to figure out so far. Any help will be really much appreciated. Thanks.

Tareq Monwer
  • 185
  • 1
  • 13
  • You can't use `getStaticProps` and `getInitialProps` at the same time, it's either one or the other. Is the `HomePage` component under the `pages/` folder? – juliomalves Jul 04 '21 at 10:52
  • @juliomalves Yes, HomePage is under pages/ directory. I have commented that "// I tried both getInitialProps & getStaticProps independently." I mean, I tried both but not at the same time. – Tareq Monwer Jul 05 '21 at 08:21

0 Answers0