Here's a solution with a good control over what's in the browser's url.
Solution consists of the following parts:
queryStringSelector
- a selector which is responsible for building
a query search string to be pushed in browser's url. It can be smart
and it can omit default values. It's possible to implement custom serialization of your values or just use JSON.stringify
.
getPartialStateFromQueryString
helper fn. It get's browser's query string and parses it into a Partial<MyState>
. It should support all of the fields encoded by queryStringSelector
and must be able to parse string values back to needed structures. It should not trust the values in URL, because users might edit these strings.
setStateFromPartialState
action in your reducer. It gets a partial state of your store (slice) as payload and updates state to match that partial state. All the values that should be in sync with URL but are not present in partial state object should be reset to initial state first.
useSyncWithUrl
custom hook. It's responsible for three main aspects. First, it sets initial value from browser url to store on component mount. That happens just once. Second, it subscribes to state changes . Basically, it consumes output of queryStringSelector
and pushes updates to URL.
Third, it updates state on URL changes. In a nutshell, it subscribes to navigation changes in browser ('POP' event) and updates store accordingly. Note that it does not react to PUSH
events, just to 'POP' event
It's essential to keep in mind that suggested approach only works well if you use your store as a source of truth. I.e. your app should apply changes to store, not to url to get to a certain state. URL is only considered as source of truth in two exceptional cases: 1) on initialization 2) when back-forward browsers' navigation happens. Though, if you navigate to some other part of the app with it's own sync hook instance, it still works because initialization phase occurs no matter how you get to the state.
Examples:
query string selector:
export const queryStringSelector = createSelector([rootSelector], (root) => {
const params = new URLSearchParams();
if (root.search !== initialState.search) {
params.append('search', root.search);
}
if (root.result_tab !== initialState.result_tab) {
params.append('tab', root.result_tab);
}
const queryString = params.toString();
if (!queryString) {
return '';
}
return `?${queryString}`;
}
getPartialStateFromQueryString
helper
const getPartialStateFromQueryString = (queryString: string): Partial<MyState> => {
const searchParams = new URLSearchParams(queryString);
const partialState: Partial<MyState> = {};
const search = searchParams.get('search');
partialState.search = search || '';
const tabString = searchParams.get('tab');
if (tabString) {
partialState.result_tab = tabString as any;
}
return partialState;
};
reducer action
const keysSyncedToUrl: (keyof MyState)[] = ['search', 'result_type', /* ... */];
//
setStateFromPartialState: (state, { payload }: PayloadAction<Partial<MyState>>) => {
// set all keys to default state first
keysSyncedToUrl.forEach((key: string) => {
state[key] = initialState[key] as any;
});
// apply partial state on top of initial state
Object.entries(payload).forEach(([key, value]) => {
state[key] = value;
});
}
sync to url custom hook:
export const useSyncWithUrl = () => {
const { search } = useLocation();
const history = useHistory();
const dispatch = useDispatch();
const [isSynced, setSynced] = useState<boolean>(false);
const queryString = useSelector(queryStringSelector);
// updates url when state changes
useEffect(() => {
if (!isSynced) {
return;
}
if (queryString !== search) {
history.push({ ...location, search: queryString });
}
}, [isSynced, queryString]);
// apply params from url on initialization
useEffect(() => {
if (!search) {
setSynced(true);
return; // no search params to restore, exit
}
const partialState = getPartialStateFromQueryString(search);
dispatch(mySlice.actions.setStateFromPartialState(partialState));
setSynced(true);
}, []);
// react on navigation events (back-forward) and restore state from url
useEffect(() => {
const unsubscribe = history.listen((location, actionType) => {
if (actionType === 'POP') {
const partialState = getPartialStateFromQueryString(location.search);
dispatch(mySlice.actions.setStateFromPartialState(partialState ));
}
});
return unsubscribe;
}, [history]);
};