the below is the getInitialProps method for MyApp.
MyApp.getInitialProps = async ({ctx}) => {
const { siteHeaderCollection } = await getHeaderData(ctx.query.lang)
const { siteFooterCollection } = await getFooterData(ctx.query.lang)
return {
locale: ctx.query.lang,
header: siteHeaderCollection,
footer: siteFooterCollection,
}
}
I need to pass the slug to this getInitialProps method. could anyone please guide on how to pass the params which are fetched from the path url
2
Answers
To pass the slug as a parameter to the
getInitialProps
method likeIn this code snippet,
slug
is extracted fromctx.query
, assuming that the slug parameter is passed as part of the URL path. You can then use thisslug
variable to fetch the appropriate header and footer data using thegetHeaderData
andgetFooterData
functions, passing thelang
andslug
as parameters.Make sure to update the
getHeaderData
andgetFooterData
functions accordingly to accept theslug
parameter and fetch the data based on the slug value.Looking at the NextJS documentation, you can find the following:
This means, whatever you return in the
getInitialProps
function will be passed asprops
in that component. (in your case,locale
,header
andfooter
)Little note:
getInitialProps
is a legacy API. NextJS recommends usinggetStaticProps
orgetServerSideProps
instead.You can access the current slug from the context:
And add it to the return object