pbeshai / use-query-params

React Hook for managing state in URL query parameters with easy serialization.

Home Page:https://pbeshai.github.io/use-query-params

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Decoding objects with keys containing underscores breaks

jtheberge opened this issue · comments

import { encodeObject, decodeObject, encodeString } from 'use-query-params';

decodeObject(encodeObject({ a: 'b_c', d: 'e' })) => {a: 'b', c: undefined, d: 'e'}
Also, encoding string does not fix this: encodeString('b_c') => b_c.

Is there a way to support underscores, or do I need to manually encode these characters inside keys?

You can just make your own ObjectParam that uses different delimiters that are safe for your values.

import {
  encodeObject,
  decodeObject
} from 'use-query-params';


const keyValueSeparator = '___' // default is "-"
const entrySeparator = '...' // default is "_"

const MyObjectParam = {
  encode: (obj) =>
    encodeObject(obj, keyValueSeparator, entrySeparator),

  decode: (str) =>
    decodeObject(str, keyValueSeparator, entrySeparator)
};

This would change:

obj = { a: 'foo', b: 'bar' }

// before: ObjectParam
encoded = "a-foo_b-bar"

// after: MyObjectParam
encoded = "a___foo...b___bar"

See serialize.ts for other available functions.

Otherwise, you can just use a JsonParam if you can't get by with the limitations of delimiters. You may even consider creating your own param that uses jsurl instead of the default JSON.stringify / JSON.parse setup.

Thank you @pbeshai I did not notice these extra params!