pbeshai / react-url-query

A library for managing state through query parameters in the URL in React
https://pbeshai.github.io/react-url-query
MIT License
194 stars 38 forks source link

Base64 decoding before mapping URL params to React props? #54

Closed jkrizanic closed 5 years ago

jkrizanic commented 6 years ago

Do you want to request a feature or report a bug? I would like to request a feature. Or please tell me how to do it if possible with current version.

What is the current behavior? Not able to map URL parameters from Base64 string (URL parameters are Base64 encoded).

What is the expected behavior? I would like to have option to provide some kind of URL preprocessing (Base64 decoding) before mapUrlToProps is called.

Which versions of react-url-query, and which browser and OS are affected by this issue? Did this work in previous versions of react-url-query? 1.4.0, and probably was not available in previous versions.

pbeshai commented 6 years ago

You can add custom decoders/encoders by setting the type to an object. See this tweet for an example.

image

If in the UrlQueryPropsConfig, it will be run before mapUrlToProps is called. Otherwise you can just do the encode/decode directly in the mapUrlToProps function.

jkrizanic commented 6 years ago

Thank you for the answer. With this approach, encode/decode will be done for every single parameter value?

pbeshai commented 6 years ago

It works the same as any other param you configure in the urlPropsQueryConfig. In the above example, the url query parameter myDate is encoded and decoded via the custom variables. You could have something like:

const base64Type = {
  encode: (data) => toBase64(data),
  decode: (base64Str) => fromBase64(base64Str)
}

const urlPropsQueryConfig = {
  myb64: { type: base64Type },
  myStr: { type: "string" },
  myNum: { type: "number" },
  myOtherB64: { type: base64Type },
}

Then myb64 and myOtherB64 will be encoded using the base64 encode/decode functions while myStr and myNum will use the built-in string and number encode/decode functions. To access these in mapUrlToProps if you want to use that method as well, you can read decode values from the props argument:

function mapUrlToProps(url, props) {
   // get the values already decoded via urlPropsQueryConfig
   const { myb64, myOtherB64, myNum, myStr } = props;
   ...
}