0

I have a small next.js project, which is served by an Express.js application. It works by exporting the Next app into static HTML (next export), and the Express server serves it as static files from a public directory.

Now the problem is, that the Next app has multiple (static) routes (/page1, /page2, ...), but nearly all pages need the same data which I fetch from an api (client side).

Now these pages look like:

export default function PageN() {
  const [ data, setData ] = useState(null)
  useEffect(() => {
    fetch(...).then((r) => {
      setData(r)
    })
  }, [])
  // ...
  if (data) {
    // render page
  } else {
    // render 'loading'
  }
}

After loading the app, and navigating from / to /page1 it fetches the data from an api. But it does that again, if navigate to /page2. The ideal solution would be fetching the required data somewhere on load, store it globally, and make it available for every page. Maybe in _app.js. I have tried experimenting with getStaticProps and getInitialProps in _app.js, but I couldn't make it work.

Is there a way to fetch data only once, and share it between every page, but still keep the ability to export the app into static HTML?

pure_bliss
  • 95
  • 1
  • 1
  • 8
  • When navigating from /page1 to /page2 is there a full page load or is the navigation done only on the client so it doesn't touch the server again? Also maybe this helps https://stackoverflow.com/questions/52238637/react-router-how-to-pass-data-between-pages-in-react – Molda Dec 15 '20 at 20:17
  • @Molda navigation is done on client side, no server touching required. Only for those fetch-es – pure_bliss Dec 15 '20 at 20:18
  • Also this https://stackoverflow.com/questions/41966762/reactjs-how-to-transfer-data-between-pages/41967180 – Molda Dec 15 '20 at 20:18
  • @Molda data transfer between pages could solve the issue, but I feel like the ultimate solution would be storing the fetched data globally somehow – pure_bliss Dec 15 '20 at 20:21

0 Answers0