Skip to content

Instantly share code, notes, and snippets.

@paprikka
Created October 16, 2017 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paprikka/8bf6d1f926b162b8896aed0ef0b3ba49 to your computer and use it in GitHub Desktop.
Save paprikka/8bf6d1f926b162b8896aed0ef0b3ba49 to your computer and use it in GitHub Desktop.
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