Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unique identifier to router instance #9015

Merged
merged 5 commits into from
Oct 30, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions packages/next/next-server/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export default class Router implements BaseRouter {
_bps: BeforePopStateCallback | undefined
events: MittEmitter
_wrapApp: (App: ComponentType) => any
historyId: number

static events: MittEmitter = mitt()

Expand Down Expand Up @@ -126,6 +127,8 @@ export default class Router implements BaseRouter {
this.sub = subscription
this.clc = null
this._wrapApp = wrapApp
// we use a historyId to enable ignoring invalid popstates
this.historyId = new Date().getTime()

if (typeof window !== 'undefined') {
// in order for `e.state` to work on the `onpopstate` event
Expand All @@ -137,17 +140,6 @@ export default class Router implements BaseRouter {
)

window.addEventListener('popstate', this.onPopState)
window.addEventListener('unload', () => {
// Workaround for popstate firing on initial page load when
// navigating back from an external site
if (history.state) {
const { url, as, options }: any = history.state
this.changeState('replaceState', url, as, {
...options,
fromExternal: true,
})
}
})
}
}

Expand Down Expand Up @@ -176,9 +168,11 @@ export default class Router implements BaseRouter {
return
}

console.log(e.state.options.historyId, this.historyId)
ijjk marked this conversation as resolved.
Show resolved Hide resolved

// Make sure we don't re-render on initial load,
// can be caused by navigating back from an external site
if (e.state.options && e.state.options.fromExternal) {
if (e.state.options && e.state.options.historyId !== this.historyId) {
return
}

Expand Down Expand Up @@ -379,7 +373,18 @@ export default class Router implements BaseRouter {

if (method !== 'pushState' || getURL() !== as) {
// @ts-ignore method should always exist on history
window.history[method]({ url, as, options }, null, as)
window.history[method](
{
url,
as,
options: {
...options,
historyId: this.historyId,
},
},
null,
as
)
}
}

Expand Down