-
Notifications
You must be signed in to change notification settings - Fork 30
/
patchRouter.ts
32 lines (27 loc) · 936 Bytes
/
patchRouter.ts
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
import { SingletonRouter, Router } from 'next/router'
import { ParsedUrlQuery } from 'querystring'
import ReactDOM from 'react-dom'
import { Store } from 'redux'
import { onLocationChanged } from './actions'
import locationFromUrl from './utils/locationFromUrl'
type RouterToPatch = SingletonRouter & { router: Router }
const patchRouter = (Router: RouterToPatch, store: Store): (() => void) => {
const unpatchedMethods = {
set: Router.router.set,
}
Router.router.set = function (...args) {
if (!unpatchedMethods.set) {
return Promise.resolve()
}
return new Promise((resolve, reject) => {
ReactDOM.unstable_batchedUpdates(() => {
unpatchedMethods.set.apply(Router.router, args).then(resolve, reject)
store.dispatch(onLocationChanged(locationFromUrl(Router.asPath)))
})
})
}
return () => {
Router.router.set = unpatchedMethods.set
}
}
export default patchRouter