N
N
NameUser2021-09-30 09:30:45
React
NameUser, 2021-09-30 09:30:45

How to dynamically pass parameter to getServerSideProps function?

Hello! There is server pagination, it is necessary to dynamically change the parameter in the URL, how can I do this?

Created a variable i in the body of the component, he does not even see it.

export async function getServerSideProps(context) {
    const products = await axios.get(`http://localhost:5000/api/card/${i}`)
        .then(res => res.data)
    return {
        props: {products}, // will be passed to the page component as props
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Sviridov, 2021-09-30
@NameUser

You must take a variable not from the body of the component. In getServerSideProps do const { query } = context; - and query will contain all query parameters from url. Here is a small example:

export async function getServerSideProps(context: any) {
    const { query } = context;
    let f: PostsListFilters = {
        limit: 24,
        offset: 0,
        order: '-publishedAt'
    };

    if (query.page) {
        f.offset = f.limit * (query.page - 1);
    }

    const posts = await postsActions.fetchPosts(f);

    return {
        props: {
            posts: posts.data,
            total: posts.meta.total,
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question