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

`updateLocation` can script crash when creating a `new URL()` #244

Closed jmcpeak closed 1 year ago

jmcpeak commented 1 year ago

Please see the diff here, at line 50:

https://github.com/pbeshai/use-query-params/commit/4d7a089b627c4e3ebc6026778bd75522f7f8ec71?diff=split#diff-2b69e8addd21fff5dab3f789e51a2582b63e95e28e393f7319e887d29de174e7

Previously href was calculated this way: const href = parseUrl(location.href || '').url + search;

Now it is this:

let href: string;
  if (location.href) {
    const url = new URL(location.href);
    href = `${url.origin}${url.pathname}${search}`;
  } else {
    href = search;
  }

If you call the updateLocation with no href, it will set href to be the search value. Now if you call updateLocation again, reusing the same location object that was returned, href will be the search value. This causes an exception at this line: const url = new URL(location.href); because URL requires a valid URL - "If the given base URL or the resulting URL are not valid URLs, the JavaScript TypeError exception is thrown." see https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

jmcpeak commented 1 year ago

PR created - https://github.com/pbeshai/use-query-params/pull/245