Next Js getStaticProps getting lost
In Next,
I have _app.js with:
const app = ({ Component, pageProps }) => {
return <div>
<Component {...pageProps} />
</div>
}
and index.js with
export default function Index({ state }) {
return (
<>
<Feed state={state} />
</>
)
}
export async function getStaticProps({ preview = false }) {
let menu = [
[
"Home",
"/"
]
[
"News",
"/news/"
]
];
state.menu = menu;
return {
props: { state, preview }
}
}
This works fine for route / but when I hit route /news the pageProps in _app.js are lost? Surely I don't have to call getStaticProps on every page?
And yes, I am a Next noob :(
The getStaticProps
method is specific to the page in question; for you, that's the home/index page (/
). So no, state.menu
won't be available for the /news
page as well.
In order for you to have the menu
state for every page, you can utilise the getInitialProps
method in _app.js
.
Like so:
// pages/_app.js
import App from "next/app";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
let menu = [
["Home", "/" ],
["News", "/news/"],
];
return {
...appProps,
pageProps: {
...appProps.pageProps,
state: { menu },
},
};
}
export default MyApp;
// pages/news.js
export default function News({ state }) {
console.log(JSON.stringify(state.menu, null, 2));
// [
// [
// "Home",
// "/"
// ],
// [
// "News",
// "/news/"
// ]
// ]
return null;
}
There are some caveats to be aware of though, so you should give that a read before going into production.