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

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, 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?