vueuse / vueuse

Collection of essential Vue Composition Utilities for Vue 2 and 3

Home Page:https://vueuse.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useRouteQuery should support array

ottopaulsen opened this issue · comments

Clear and concise description of the problem

Some times a query param can have multiple values: ?state=NEW&state=OLD
In this case you may want to always get an array if you read the query param, either an empty array or an array with one or more values. Two in the example.
However, what you get is a string if there is only one value, and an array only if there are multiple values. If you use useRouteQuery with {transform: Array} you get an array if there is 0 or 1 values, but if there are multiple values you get an array with an array.

Suggested solution

Fix so if {transform: Array} is used, it always returns a flattened array.

Alternative

No response

Additional context

No response

Validations

useRouteQuery just calls the passed transform function without carrying about a value. And I don't think the composable should change anything because vue-router does query params stringifying/parsing by itself and then passes to the consumers.

You can check the URL by calling router.push() with the query params { state: ['test'] } and { state: 'test' } passed to the default parser/stringifier of vue-route. They are equal and the output can have array or string type depending on conditions.

You have two options to achieve what you want:

  1. To create a function that will transform a value accurately:
const toArray = (param: LocationQueryValue | LocationQueryValue[]) =>
  Array.isArray(param) ? param : [param];
const type = useRouteQuery('state', [], { transform: toArray });
  1. To use another parser/stringify function in a router configuration: https://router.vuejs.org/api/interfaces/RouterOptions.html#parseQuery. One of the popular options is qs that works with query params more flexible and handles difference between different query params types described above.