Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shared router event subscriptions in Next.js
// usage:
// 1. import in your page/component/layout
// 2. subscribe in componentDidMount
// 3. make sure you unsubscribe in componentWillUnmount
import Router from 'next/router'
import { Observable } from 'rxjs'
console.log('route: initialising router')
export const routeChangeStart$ = Observable.create(
obs => {
console.log('route: start')
Router.onRouteChangeStart = url => {
obs.next(url)
}
}
).share()
export const routeChangeComplete$ = Observable.create(
obs => {
Router.onRouteChangeComplete = () => {
console.log('route: complete')
obs.next()
}
}
).share()
export const routeChangeError$ = Observable.create(
obs => {
Router.onRouteChangeError = () => {
console.log('route: error')
obs.next()
}
}
).share()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.