How to add queryPrams with previous query into next js router?

Viewed 19

here suppose I have a dynamic router like [index] under category folder. Here dynamic index will be category slug. Now I have to add more query prams in this url.

First link will be like-

/category/men-and-women

Now I have to add to this url some query with router.push method will be like-

/category/men-and-women?soryBy=price

Then I have to also add some more query prams with this previous url like-

/category/men-and-women?sortyBy=price&maxPrice=1232

How can I add more and more query prams with previously stored prams?

I tried two ways-

router.push({
    pathname: `/category/${router.query.index}`,
    query: {
        minPrice: value[0],
        maxPrice: value[1]
    }
})

It works good. But when I try to add more query prams. I am stacking-

router.push({
    pathname: router.asPath,
    query: {
        sortBy: "price"
    }
})

I try it by this way. But it not working.

1 Answers

You need to get the current params and append them:

const router = useRouter();

// ...

router.push({
    pathname: router.asPath,
    query: {
        ...router.query,
        sortBy: "price"
    }
})
Related