1

I'm currently converting my React.js project into Next.js.

I'm running into a few issues with props at the moment though.

Previously with React, I made API calls at app.js then passed it down into the navbar to be used in a search form.

With Next.js there's not really an option since API calls are blocked from the _app.js file. Which is where my layout.js (Nav/Footer).

options I'm considering:

  1. change the convention of the index.js file to be like the app.js instead of the home.js page.
  2. wrapping the layout on every page instead of wrapping _app.js and calling stock API on every page.

I feel like there's a better way to just call the API once and pass it to the necessary children. If someone can give me any recommendation on how to combat top-level sharing of props that would be great!

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Peter Chavez
  • 53
  • 1
  • 7
  • Try to create custom `_document` file, [read more here](https://nextjs.org/docs/advanced-features/custom-document). – hisam Sep 18 '21 at 02:55
  • Does this help answer your question: [Persistent navigation in a NextJs \_app](https://stackoverflow.com/a/65628271/1870780)? You can use [`getInitialProps`](https://nextjs.org/docs/api-reference/data-fetching/getInitialProps) in your custom `_app` to make the API calls. – juliomalves Sep 18 '21 at 16:56
  • 1
    @juliomalves I appreciate that. I believe that is exactly what I need! Awesome! – Peter Chavez Sep 21 '21 at 20:38

1 Answers1

0

Consider doing the following

1.If the props are needed pervasively in the app eg. theme or auth object, create a Context provider and wrap the _app.js component with it.

2.If the props are needed in only few components, find the closest common ancestor and make the fetch there like you would normally do in React. additionally, in Nextjs, you can use getServerSideProps to pre-render pages on every request

RobLjm
  • 399
  • 2
  • 11
  • Yes, I needed them for my Layout.js as well as every page so I believe using context.Provider or the `getInitialProps` would work at the `_app.js` level. Thanks! – Peter Chavez Sep 21 '21 at 20:41
  • Ok, but be warned that the official docs don't recommend `getInitialProps` at the _app.js unless you have a blocking data requirement for every page. Doing so will server-side render every page and you will the benefit of automatic static generation of non-data blocking pages eg About page, FaQ page etc – RobLjm Sep 22 '21 at 02:22