mobx-react-routing
Version:
MobX react-router-dom integration
52 lines (51 loc) • 1.61 kB
JavaScript
import { action, makeObservable, observable, runInAction } from 'mobx';
export class QueryParamsBase {
router;
data;
routerSubscription;
constructor(router) {
this.router = router;
this.data = this.getSearchParamsData();
observable.struct(this, 'data');
action(this, 'set');
action(this, 'update');
makeObservable(this);
this.routerSubscription = this.router.subscribe(() => {
runInAction(() => {
this.data = this.getSearchParamsData();
});
});
}
getSearchParamsData(search = location.search) {
return Object.fromEntries(new URLSearchParams(search).entries());
}
buildSearchString(data) {
const fixedData = {};
for (const [key, value] of Object.entries(data)) {
if (value != null) {
fixedData[key] = value;
}
}
const urlSearchParams = new URLSearchParams(fixedData);
return urlSearchParams.size > 0 ? `?${urlSearchParams}` : '';
}
buildUrl(queryParams) {
const search = this.buildSearchString(queryParams);
return `${location.pathname}${search}`;
}
set = async (queryParams, replace = false) => {
const nextUrl = this.buildUrl(queryParams);
await this.router.navigate(nextUrl, {
replace,
});
};
update = async (queryParams, replace = false) => {
await this.set({
...this.data,
...queryParams,
}, replace);
};
destroy() {
this.routerSubscription();
}
}