baruchiro / use-route-as-state

Use React Router route and query string as component state
https://baruchiro.github.io/use-route-as-state/
MIT License
42 stars 7 forks source link

Setting default values in URL #135

Closed louis-sanna-eki closed 3 years ago

louis-sanna-eki commented 3 years ago

Use case

I would like to uniquely sync the state with the URL (modulo param permutation). This is not the case when using default, the same state can lead to two distinct url.

Current behavior

For instance on demo page (https://github.com/baruchiro/use-route-as-state), const [foo, setFoo] = useQueryStringKey('foo', 'bar'), the default value of foo (bar) does not show up in the URL on page load. Then after manual update is does.

First page load:

Screenshot 2021-09-26 at 11 56 10 Screenshot 2021-09-26 at 12 03 15

After changing the foo in input and setting it back to bar.

Screenshot 2021-09-26 at 11 56 16 Screenshot 2021-09-26 at 11 56 05

Any reco on how to make sure the URL is https://baruchiro.github.io/use-route-as-state/?foo=bar on page load?

baruchiro commented 3 years ago

Hi, thank you for using the library and sharing with me your concern!

First, you can open the Flow.drawio file with diagrams.net - Draw.io, to see when we assigning the default values into the returned object.

I don't remember exactly the decisions I made. Let's think.

  1. How do you expect me to support that? By adding an options object to enable showing the default values?
  2. What about you will not configure a default value, and instead, you will add a useEffect to set the value when the component is mounted? (I'm asking to understand the use-case).
louis-sanna-eki commented 3 years ago

@baruchiro

  1. I expected it to be the default behaviour.
  2. Yes you're right, a simple useEffect is enough for my use-case, I hoped there was a better way to do it.

Thanks for having taken the time to look at this issue.

(I'm leaving the issue open, but don't hesitate to close if you want)

baruchiro commented 3 years ago

OK then, thanks @louis-sanna-eki for your suggestion. I understand it, but I chose to take the another approach, which is also logical, so I will not change it for now.

Thanks again, and feel free to open other issues!