url
This package provides a set of helpers to be sync with the url, search parameters, change it and react to it changes.
Installation
#Usage
#Base primitive is urlAtom
, it contains URL
and by default initiates with a browser location.href
(see Behavior for details).
You can call the urlAtom.go
action with a root path to navigate programmatically.
Search parameters
#There is also searchParamsAtom
which derives from urlAtom
and allow you to handle search params reactively. You could pick needed parameter by searchParamsAtom.lens
method just by passed key or specify the type of the parameter by providing optional parse
and serialize
functions.
In the code below filterAtom
is a mutable atom which changes will be synced with the passed search parameter. If you want to setup the sync for some other atom, you could use withSearchParamsPersist
decorator.
Now you have handy increment
and decrement
actions in pageAtom
and synchronization with “page” search parameter.
Also, both searchParamsAtom.lens
and withSearchParamsPersist
accepts options object by the second argument, which you can use to specify replace
strategy (false
by default).
Types
#Here are the types of the key features.
Behavior
#When urlAtom
is first read (directly or indirectly through searchParamsAtom
), a subscription to the popstate
event and interception of the document.body
click appears. If you don’t want to handle and prevent link clicks, you could call setupUrlAtomBrowserSettings(ctx, /* shouldCatchLinkClick: */false)
action.
If you need to run your code in a different environment (unit tests or SSR) you could replace the url handling behavior by calling setupUrlAtomSettings
action with a function for getting URL (init
parameter) and optional sync
parameter for subscription to URL change.
Integrations
#By default urlAtom uses window.location
as the source of truth (SoT). But if you using any other router manager, you should setup reactive integrations by yourself, as the native location
API is not reactive and can’t be used as the SoT.
To put the new URL from the the source of truth to urlAtom
you should always use updateFromSource
action, because only this updates will not be synced back and it will help you to prevent cyclic stack.
Here is the example of integration with https://reactrouter.com. Put this component in the top of your application tree (as a child of RR provider and Reatom provider)!
You could play with it in Tanstack VS Reatom example
The warning Cannot update a component while rendering a different component ("RouterSync")
is ok, there are no way to write it in another way and fix it, as the Router.subscribe
method is deprecated.