10

I want to create an url from query params in the next way:

 router.push(
      {
        pathname: '/cars',
        query: colors + type + price,

      },
      undefined,
      {
        shallow: true,
      },
  );

const colors = ['red', 'blue', 'yellow']; //the arrays could contain many others values
const type = ['offroad', 'sport'];
const price = 'hight'  //this is a string

I want to achieve, when i will click the button which trigger the router.push, the next: /cars?color=red,yellow,blue&type=offroad,sport&price=hight

5
  • 1
    how will you get the query if you have same key for multiple values? Commented Nov 1, 2020 at 17:41
  • @Shyam, what do you mean? Commented Nov 1, 2020 at 17:48
  • if you have query as color=red&color=blue how will you parse them? I will suggest you to have it in this format /cars?colors=red,blue,green&type=sports Commented Nov 1, 2020 at 17:54
  • @Shyam, i got what you mean, but i need a solution for the situation that i've described above. Could you help? Commented Nov 1, 2020 at 18:00
  • query param must be a valid object. in your case you have same key for multiple value which will be overridden. Commented Nov 1, 2020 at 18:08

4 Answers 4

11

you can simply do:

 const router = useRouter();
 router.push(
  {
    pathname: '/cars',
    query: {
      colors,
      type,
      price,
  },
  undefined,
  {
    shallow: true,
  },

);

According to Next/Router type, query is typeof ParsedUrlQuery which equivalent to

interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> { }

That is to say, next/router is able to parse both string and array of strings

Sign up to request clarification or add additional context in comments.

1 Comment

Lue, thanks, could you take a look stackoverflow.com/questions/64662714/…
5

If you have a dynamic route and want to be able to use this universally, for example, some link on every page (in the header) you can achieve this by providing all currently available route params and add or replace the additional or existing one.

// ...
const router = useRouter();
// ...

<Link
    href={{
        pathname: router.pathname,
        query: { ...router.query, colors, type, price },
    }}
    passHref
    shallow
    replace
></Link>

Comments

1

If you store your params with repeating keys Next.js will recognize it as an array

router.query = color=red&color=green&color=blue
router.push(router)
router.query -> ["red", "green", "blue"]

If you store your params with the same key they will be stored as a single string:

router.query="color=red,green,blue"
router.push(router)
router.query -> red,green,blue

If you want your param key items to be stored in an array:

const params = []
const colors = ['red', 'blue', 'yellow'].map(color => `color=${color}`).join("&")
const type = ['offroad', 'sport'].map(type => `type=${type}`).join("&")
const price = 'hight'

colors && params.push(colors)
type && params.push(type)
price && params.push(price)

const paramsString = params.join('&')
router.params = paramsString
router.push(router)

// This code would result your query.params to be:
query.params -> {color: ['red', 'green', 'blue'], type: ['offroad', 'sports'], price:'hight'}

If you want your param key items to be stored as a string:

const colors = ['red', 'blue', 'yellow']
const type = ['offroad', 'sport']
const price = 'hight'

router.query.colors = colors.join(',')
router.query.type = type.join(',')
router.query.price = price
router.push(router)

// This code would result your query.params to be:
query.params -> {color: 'red,green,blue', type:'offroad,sports', price:'hight'}

Comments

0

https://nextjs.org/docs/api-reference/next/router#with-url-object

you try this

router.push({
          pathname: '/cars',
          query: {
              colors: colors.join(","),
               types: types.join(",")
           },
 }) 

3 Comments

Explain please?
router.push resolves your query object to query string. so it will be converted from` { colors : red, blue, type: sports}` to colors=red, blue&type=sports
@Shyam, but how to get /cars?color=red&color=yellow&color=blue&type=offroad&type=sport&price=hight?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.