Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global place to fetch menu items in NextJs from getServerSideProps or getStaticProps

Is there any global place in Next.js to fetch menu-items(server-side) that I can pass to my Layout component.

Since, I can't do that in index.js as if somebody directly opens different route for eg: /about then the data will not be fetch.

I tried doing that in _app by implementing it's static getInitialProps method but I'm not sure if it's a good practice and also it will disable Automatic Static Optimization in pages without Static Generation.

Any suggestion?

like image 995
Shubham Chitransh Avatar asked Aug 31 '20 10:08

Shubham Chitransh


People also ask

What is the difference between getstaticprops and getserversideprops in next JS?

In Next js, data fetching is a strategy. Next.js uses getStaticProps or getServerSideProps to enhance different fetching capabilities. Even though both are used to pre-render data, the former uses static generation whilst the latter uses server side rendering. Hmm... ok but do I need page pre-rendering?

What is next JS used for?

Next.JS is a tool employed primarily to build server-side rendered websites that generate the HTML dynamically through a server during every instance of receiving a new request. Data fetching in Next.js allows you to render your content in different ways, depending on your application’s use case.

Can I use fetch () to all API routes in getserversideprops ()?

But then I read in the Next.js documentation that you should not use fetch () to all an API route in getServerSideProps (). You want to use the logic that's in your API route directly in getServerSideProps, rather than calling your internal API.

When to use import in getserversideprops?

This is useful if you want to fetch data that changes often, and have the page update to show the most current data. You can import modules in top-level scope for use in getServerSideProps. Imports used will not be bundled for the client-side.


1 Answers

getInitialProps is the old way of what you are doing to do. But getServerSideProps and getStaticProps will replace getInitialProps

getInitialProps seem to be deprecated soon https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

But getServerSideProps can't be used in _app for global data fetching for now. It will be introduced later. Until then, I think you have these options:

  1. Keep using getInitialProps and trade static optimization
  2. Get the menu items on the client side and render an activity indicator (a spinner?) until the data is ready.
  3. Add a getServerSideProps wrapper and a HoC like withMenuItem and wrap all pages and their getServerSideProps exports.
like image 104
Gokhan Sari Avatar answered Oct 18 '22 06:10

Gokhan Sari