Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't clear ArrayParam state when default value is not empty #248

Open
oleksiy-letushev-axon opened this issue Nov 1, 2022 · 2 comments

Comments

@oleksiy-letushev-axon
Copy link

oleksiy-letushev-axon commented Nov 1, 2022

When I have an ArrayParam state with a non-empty default array, I can't make it empty

const Arr = withDefault(ArrayParam, ["bar"]);

const Demo = () => {
  const [state, setState] = useQueryParam("foo", Arr);

  return (
    <div>
      <p>State: {JSON.stringify(state)}</p>
      <button
        onClick={() => {
          setState([]); // doesn't work
        }}
      >
        Clear state
      </button>
    </div>
  );
};

https://codesandbox.io/s/gallant-shockley-w2yojs?file=/src/App.js

@pbeshai
Copy link
Owner

pbeshai commented Nov 1, 2022

Empty arrays are tricky since there isn't really any invertible options from URLSearchParams or even query-string. How would you encode them in the array and get them decoded? Consider this code

      <p>URLSearchParams encode foo []: {JSON.stringify(new URLSearchParams({ foo: []}).toString())}</p>
      <p>URLSearchParams decode foo=: {JSON.stringify(new URLSearchParams("?foo=").get('foo'))}</p>
      <p>URLSearchParams decode foo=: {JSON.stringify(new URLSearchParams("?foo=").getAll('foo'))}</p>
      <p>query-string stringify encode foo []: {JSON.stringify(stringify({ foo: [] }))}</p>
      <p>query-string stringify decode "": {JSON.stringify(parse("")).foo}</p>

Screenshot 2022-11-01 at 11 30 54

I'm not really sure there's anything obvious we can do in the library to circumvent this. That being said, if you setState(['']) it will be decoded as [] in your sandbox and encoded in the URL as ?foo=

@oleksiy-letushev-axon
Copy link
Author

Looks tricky but it works at least. Many thanks 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants