In my nextjs project, I have the Layout component that needs api call. Instead of calling api calls in every pages(./pages/*), I'd like to put the logic in some global space. I researched a bit, and it looks like overriding _app.js is the way to go indicated in nextjs documentation(https://nextjs.org/docs/advanced-features/custom-app).
I have laid out code as below. But it doesn't seem to work.
./pages/_app.js
function MyApp({ Component, appProps, results }) {
return (
<Layout {...results}>
<Component {...appProps} />
</Layout>
)
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext)
const results = await getResults() //api call
return { appProps, results }
}
./components/Layout.js
const Layout = ({ children, results }) => {
return (
<React.Fragment>
<Header/>
<div className='row col-md-8 offset-md-2'>
{JSON.stringify(results)} //results is nothing here
<div className='col-md-9'>
{children}
</div>
</div>
</React.Fragment>
)
}
./pages/index.js
...
return (
<>
{head()}
<Layout>
<div className='row col-md-12'>
{showContents()}
</div>
</Layout>
</>
)
I'm sure I'm missing some obvious things. Any help would be appreciated.