hassan moradnezhad
hassan moradnezhad

Reputation: 577

context parameter is empty on getServerSideProps when page refresh

In one of my projects, I need to fill the meta keyword and the meta description by the data which is fetched from a REST API request.
so I used the getServerSideProps function, to fetch the response and pass it to the page.
Here's my getServerSideProps function

export async function getServerSideProps(context) {


    function makeParam() {
        let params = new URLSearchParams(context.params);
        let keysForDel = [];
        params.forEach((v, k) => {
            if (v === 'undefined')
                keysForDel.push(k)
        });
        keysForDel.forEach(k => {
            params.delete(k)
        });
        return params.toString()
    }

    let response = await axios.post(
        process.env.baseAddress + "getData.php",
        qs.stringify({
            data: "api/search/advance?" + makeParam()
        }),
        {
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            }
        })

    return {
        props: {
            dataFromServer: response.data,
            params: makeParam()
        },
    }
}

everything works fine in development mode (localhost), but after deploying, by refreshing the page Context parameter is an empty object.
this function was written in one of the pages that has one parameter called the city, which is shown below
page file

I have already checked getServerSideProps props empty object. as Ankri said

Can you please check, that you pass the pageProps to your custom Component?

here is my Component tag, which contains pageProps.

<Layout>
    <Component {...pageProps} ref={current}/>
</Layout>

Upvotes: 0

Views: 2226

Answers (1)

Paiman Rasoli
Paiman Rasoli

Reputation: 1214

First make the file structure like this:

pages:
  city:
   [...slug].js

Note: city is folder!

Now you can get the first param like this:

export async function getServerSideProps(context) {
 const slug = context?.query?.slug[0] || "";
 const req = await axios.post(`${url}?advance=${slug}`)
 // ... rest of the code 
}

now if url looks like this => http://localhost:300/city/japan slug = japan

Upvotes: 0

Related Questions