Janne
Janne

Reputation: 1011

Tanstack Router Link with search params where one key has multiple values

I'd like to provide a search property to my Link component where they query string key can have multiple values (an array)

<Link to="/foo/bar" search={{group_by: ['foo', 'bar']}} ...>

This does work, but the query string in the browser is shown like this:

?group_by=%5B"foo"%2C"bar"%5D

It does work technically. But I'd like it to be:

?group_by=foo&group_by=bar

but I don't know how to make that happen. If I try to set the query string to the to property

<Link to="/foo/bar?group_by=foo&group_by=bar" ...>

I get a type error (I'm using typescript) that the route is not any of those I've defined in my router config.

Upvotes: 0

Views: 511

Answers (1)

David Ferreira
David Ferreira

Reputation: 1786

You have to use a Custom Search Param Serialization. You can do it alongside the query-string library. (See: https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization#using-the-query-string-library)

The query-string library allows you to specify the format for arrays, I think the 'none' format (which is the default) is the one that you want.

To remove the encoding, you can set the encode option to false.

Example:

import { createRouter } from '@tanstack/react-router'
import qs from 'query-string'

const router = createRouter({
  // ...
  stringifySearch: stringifySearchWith((value) =>
    qs.stringify(value, {
      arrayFormat: 'none', // default, can be ommitted
      encode: false
      // ...options
    }),
  ),
  parseSearch: parseSearchWith((value) =>
    qs.parse(value, {
      // ...options
    }),
  ),
})

Play with the options to get what you expect.

There is another library similar to query-string called qs. Even though it doesn't support the array format that you want, it has some other array formats and also allows you to encode only the values with its encodeValuesOnly option.

Upvotes: 0

Related Questions