-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoutingContext.js
36 lines (30 loc) · 1.01 KB
/
RoutingContext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import BaseContext from './BaseContext';
import qs from 'querystringify';
export default class RoutingContext extends BaseContext {
constructor() {
super({
path: window.location.pathname,
query: RoutingContext.parseQuery(window.location.search)
});
this.navigate = this.navigate.bind(this);
console.log('RoutingContext initialized:', this.value);
}
static parseQuery(search) {
return qs.parse(search.startsWith('?') ? search.slice(1) : search);
}
static stringifyQuery(query) {
const queryString = qs.stringify(query);
return queryString ? `?${queryString}` : '';
}
navigate(path, query = {}, pushState = true) {
const search = RoutingContext.stringifyQuery(query);
console.log('Navigating to:', path, query);
if (pushState) {
window.history.pushState({}, '', `${path}${search}`);
} else {
window.history.replaceState({}, '', `${path}${search}`);
}
this.updateValue({ path, query });
}
}
export const routingContext = new RoutingContext();