skip to Main Content

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


  1. To pass the slug as a parameter to the getInitialProps method like

    MyApp.getInitialProps = async ({ ctx }) => {
        const { query: { lang, slug } } = ctx; // Retrieve the slug from the 
        query object
    
        // Fetch header and footer data using the slug
        const { siteHeaderCollection } = await getHeaderData(lang, slug);
        const { siteFooterCollection } = await getFooterData(lang, slug);
    
        return {
            locale: lang,
            header: siteHeaderCollection,
            footer: siteFooterCollection,
        };
    };
    

    In this code snippet, slug is extracted from ctx.query, assuming that the slug parameter is passed as part of the URL path. You can then use this slug variable to fetch the appropriate header and footer data using the getHeaderData and getFooterData functions, passing the lang and slug as parameters.

    Make sure to update the getHeaderData and getFooterData functions accordingly to accept the slug parameter and fetch the data based on the slug value.

    Login or Signup to reply.
  2. Looking at the NextJS documentation, you can find the following:

    getInitialProps is an async function that can be added to the default exported React component for the page. It will run on both the server-side and again on the client-side during page transitions. The result of the function will be forwarded to the React component as props.

    This means, whatever you return in the getInitialProps function will be passed as props in that component. (in your case, locale, header and footer)

    Little note: getInitialProps is a legacy API. NextJS recommends using getStaticProps or getServerSideProps instead.

    You can access the current slug from the context:

        const { query: { lang, slug } } = ctx;
    

    And add it to the return object

     return {
            slug,
            locale: lang,
            header: siteHeaderCollection,
            footer: siteFooterCollection,
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search