0
votes

So basicly we have an initial fetch in our custom pages/_app.jsx that first fetches sitesettings & navigation for header/footer. This data I would like to be only fetched once however it gets fetched every routechange clientside. Is there anyway to persist some data after the initial fetch in the app container?

Here's my code:

import React from 'react'
import App, { Container } from 'next/app'
import Header from '../components/Header';
import Footer from '../components/Footer';

class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {}

    const res = await fetch(`http://localhost:3000/navigation`)
    const nav = await res.json();

    const ss = await fetch(`http://localhost:3000/site-settings`);
    const settings = await ss.json();

    var culture = "en-us";
    var root = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
      if (pageProps && pageProps.pageContext) {
        culture = pageProps.pageContext.culture || "en-us";
        root = nav.message.find(nav => !nav.parentPage && nav.culture === culture);
      }
    }

    return { 
      pageProps, 
      navigation: nav.message,
      settings,
      culture,
      root
    }
  }

And the issue is that the getInitialProps of my _app.jsx is being run at every route making unecessary requests to fetch data that client already have.

1
Fetch you data in _document insteadevgeni fotia
@joelgullander I am facing a similar issue. Can you share what strategy did you follow?Gurmeet Singh

1 Answers

1
votes

There are three separate issues here: first, performing the fetch in _app will guarantee execution for every page, since it is used to initialize each page. That is not what you want. Instead this should happen in the appropriate page.

Second, this shouldn't happen in getInitialProps as that delays the loading of the page. If that is intended, go ahead and do it - but it would be better practice to render the page ASAP, and fill in the gaps later, rather than showing a blank screen.

Third, and most important, you need to load the information you need and manage it in some sort of application state that is shared between all pages. That can be done in redux, React Context, or your own solution for storing the received information if the other solutions feel like overkill for your project. That way you can check if you have it before fetching, and only fetching once.