0

sorry if the title is not very clear. I try to explain myself: my site is built with Next.js and retrieves data from Sanity Studio (CMS). In Sanity the user can create menu items. I have a menu in the footer component, one in the sidebar component and another one in the header component. The thing is, I can fetch sanity only in pages. So I created a function that, with each build, creates a JSON with all the information entered by the user. Next, to have the menu items throughout the site, this JSON is imported into the "Layout" component and stored in a specific react context. And everything works fine. But I noticed one thing: if I look in the source code of the page, the menu looks like this:

<nav>
<ul></ul>
</nav>

even though it is rendered perfectly in HTML. I guess it is because I generate the JSON server side and when the page is created that information is not available.

Any ideas?

Thank you

EDIT: this is the Layout component where I imported the JSON file

import styles from '@styles/components/Layout.module.css';
import React from 'react';
//other imports...

//imported JSON
import globalData from '@client/global-manifest.json';

//this is the normalize function
import { normalizeNavigationFromRaw } from '@utils/normalizeNavigation';

//this is the navigation normalized
const navigationData = normalizeNavigationFromRaw(globalData?.navigation ?? {});


export default function Layout({ children }: { children: React.ReactElement }) {
  // some functions for open/close modal ...

  //context method to store navigation
  const { setNavigation } = React.useContext<any>(GlobalSettingsContext);


  //store navigation in context
  React.useEffect(() => {
    setNavigation(navigationData);
  }, []);

  return (
    <>
      <Head>
        // some head code

      </Head>
      
      <main className={styles.container}>
        <HeaderWrapper
          toggleMenu={toggleMenu}
          toggleContactPanel={toggleContactPanel}
        />
        <SidebarMenu
          isOpenMenu={isOpenMenu}
          toggleMenu={toggleMenu}
          ref={sideMenuRef}
        />
        <ContactPanel
          isOpenContact={isOpenContact}
          toggleContactPanel={toggleContactPanel}
          ref={panelRef}
        />
        {children}
      </main>
      <Footer />
    </>
  );
}

the other components involved have only the navigation context imported from useContext and used. For example the footer:

import * as React from 'react';
//other imports...

import { GlobalSettingsContext } from '@contexts/GlobalSettings';

export default function Footer(): React.ReactElement {
  const { navigation } = React.useContext(GlobalSettingsContext);

  return (
    <footer
      className={
        isSingleVehiclePage
          ? `${styles.footer} ${styles.morePadding}`
          : styles.footer
      }
    >
      <LayoutContainer>
        <div className={styles.secondary}>
          <div className={styles.social}>
            {navigation.footerSocialIcon &&
              navigation.footerSocialIcon.map((el: any, mainKey: number) => (
                <Link key={mainKey} to={el.titleLink ?? ''}>
                  <span className={`icon-${el.iconClass ?? ''}`}></span>
                </Link>
              ))}
          </div>
        </div>
      </LayoutContainer>
    </footer>
  );
}

5
  • We need more info for a clearer picture. please add the code of the nextjs page so we can help you Commented Jan 5, 2022 at 19:13
  • Hi, I did not add code because I dont know what part of code to add. I mean, in the Layout component I imported the json file created server side at build time with a regular import: import globalData from '@client/global-manifest.json'; and store it in a context. It is rendered correctly in every page, but in the source code the html tag <ul> is empty. Only when click "inspect source page"; in the page rendered I see the list items. It is a problem just for SEO. Commented Jan 5, 2022 at 19:48
  • I insist on seeing the code (of all the "components" involved). Something is not working so what you are saying you did may very well not be what the code is actually doing. From what you are telling me, i can only guess, and with the current description, my guess is that by using react context, you are injecting the JSON after rehydration, which means it wont be in the source code. Commented Jan 5, 2022 at 19:51
  • Ok, thank you. I added the relevant code for the navigation in the Layout component. Commented Jan 5, 2022 at 20:10
  • I could give a more detailed answer if you added an snippet of the page component, with the getStaticProps or getServerSideProps function Commented Jan 5, 2022 at 21:54

1 Answer 1

1

From the provided description i assume you are using getStaticProps. (although the it would be basically the same issue for getServerSideProps)

In order for data fetched to be pre-rendered in html, you need to pass it as props, returning it from getStaticProps.\

What you are doing is passing data to a react context, which is rendered after hydration takes place.
I advise you to review the basics of nextjs to understand what code is executed in the client and which is executed in the server, along with how pre-rendering works. please check https://nextjs.org/docs/basic-features/pages

3
  • The components that use the data from the context are inside the Layout component..the Layout component is a wrapper and it is in the _app file. The _app file returns: <GlobalSettingsProvider> <Layout> <Component {...pageProps} /> </Layout> </GlobalSettingsProvider> I tried using getStaticProps in _app but I cant use context.I tried pass the data via props to Layout from _app and than store it in the context inside the Layout component;still nothing in the source.And I can use getStatiProps only in pages not in the footer or header component (where I need the data from sanity) Commented Jan 6, 2022 at 0:04
  • 1
    @user16469315 The issue is you're setting the data into context from inside a useEffect which only runs on the client-side. Pass the data directly into the GlobalSettingsContext's provider value instead. Commented Jan 7, 2022 at 19:04
  • @juliomalves Thanks a lot man, it works!! Commented Jan 7, 2022 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.