pbeshai / use-query-params

React Hook for managing state in URL query parameters with easy serialization.
https://pbeshai.github.io/use-query-params
ISC License
2.13k stars 95 forks source link

Update Url without encoding the values #254

Closed MichaelHefetz closed 1 year ago

MichaelHefetz commented 1 year ago

Is it possible to update Url with the original value and not the encoded one?

For example 'a:2:c' not to be encoded as a%3A2%3Ac when updated in Url

We need to use filters in rison format instead of json in Url like Kibana does

so I tried to create custom param.

export const RisonParam = {
  encode: (any: any | null | undefined): string | null | undefined => {
    if (any == null) {
      return any;
    }

    return rison.encode(any);
  },

  decode: (input: string | null | undefined): any | null | undefined => {
    let result = null;
    try {
      result = rison.decode(input);
    } catch (e) {
      /* ignore errors, returning undefined */
    }

    return result;
  },
};

rison.encode(any) returns decoded value, but in Url we get encoded string with %

pbeshai commented 1 year ago

You should be able to accomplish this with the objectToSearchParams option (set at the provider)

Here's an example using query-string, but you can do whatever you like

import { parse, stringify } from 'query-string'
import {
  QueryParamOptions,
  QueryParamProvider,
  transformSearchStringJsonSafe,
} from 'use-query-params'

const useQueryParamsOptions: QueryParamOptions = {
  objectToSearchString: (obj) => {
    const searchString = stringify(obj)
    // add {}[],": back
    const jsonSafe = transformSearchStringJsonSafe(searchString)
    // add dollar signs back
    const result = jsonSafe.replace(/%24/g, '$')
    return result
  },
  searchStringToObject: parse,
}

...

 <QueryParamProvider options={useQueryParamsOptions} ...>

The provided helper from this package transformSearchStringJsonSafe allows {}[],": in URL query params.

Note if you're not using query-string, you can use the default objectToSearchString exported from the package instead of stringify

MichaelHefetz commented 1 year ago

Thank you, will try!

update: it works, thank you