[SOLVED] How to Server Side load data in App.js next.js

Issue

This Content is from Stack Overflow. Question asked by AMunim

I have a layout component that is loaded once on App.jsx and stays the same throughout the session, but since the page is SSRed it loads first, then the layout displays after a second, is there a way to get the layout data along with the page without having to add it to every page?

function MyApp({ Component, pageProps: { session, ...pageProps } }) {
  const abortController = new AbortController();
  const signal = abortController.signal;
  const [content, setContent] = useState();
  const router = useRouter();
  console.log("url", router);
  useEffect(() => {
    const fetchUIContent = async () => {
      let data;
      let responseStatus;
      try {
        data = await axios.get("/api/layout", {
          httpsAgent: new https.Agent({ rejectUnauthorized: false }),
          signal: signal,
        });
        responseStatus = data.status;
      } catch (error) {
        if (error.name === "AbortError") return;
        console.log("Error message:", error.message);
      } finally {
        if (responseStatus == 200) {
          setContent(await data.data);
        } else {
          console.log("Oops error", responseStatus, "occurred");
        }
      }
    };

    fetchUIContent();

    return () => {
      abortController.abort();
    };
  }, []);
  return (
    <Provider store={store}>
      <SessionProvider session={session} /*option={{clientMaxAge: 10}}*/>
        <ConfigProvider direction="ltr">
          <HeadersComponent>
            <Layout content={content}>
              <Component {...pageProps} />
            </Layout>
          </HeadersComponent>
        </ConfigProvider>
      </SessionProvider>
    </Provider>
  );
}

I thought of using redux to get the layout data, but that would still need to make changes on each page and it is a pretty large project.



Solution

Fixed by https://github.com/vercel/next.js/discussions/39414
For Future readers, this is how to add extra props for use in MyApp

//to consume foo
function MyApp({ Component, pageProps, foo }) { //if you have {Component, pageProps: { session, ...pageProps }, foo} make sure foo is outside the pageProps destructure
  return (
          <MyFooConsumer foo={foo}>
            <Component {...pageProps} />
          </MyFooConsumer>
           )
}

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

  return { ...appProps, foo: 'bar' }
}


This Question was asked in StackOverflow by AMunim and Answered by AMunim It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?