Unverified Commit 2d0ad7d4 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Refactor Router#getInitialProps (#9853)

This PR refactors `Router#getInitialProps` in preparation for dedicated SSG fetching logic. This PR should have no functional change -- please review it carefully.
parent 356e5caf
...@@ -624,25 +624,42 @@ export default class Router implements BaseRouter { ...@@ -624,25 +624,42 @@ export default class Router implements BaseRouter {
return Component return Component
} }
async getInitialProps( _getData<T>(fn: () => Promise<T>): Promise<T> {
Component: ComponentType,
ctx: NextPageContext
): Promise<any> {
let cancelled = false let cancelled = false
const cancel = () => { const cancel = () => {
cancelled = true cancelled = true
} }
this.clc = cancel this.clc = cancel
const { Component: App } = this.components['/_app'] return fn().then(data => {
let props if (cancel === this.clc) {
this.clc = null
}
if (cancelled) {
const err: any = new Error('Loading initial props cancelled')
err.cancelled = true
throw err
}
return data
})
}
getInitialProps(
Component: ComponentType,
ctx: NextPageContext
): Promise<any> {
const { Component: App } = this.components['/_app']
const AppTree = this._wrapApp(App)
ctx.AppTree = AppTree
return this._getData(() => {
if ((Component as any).__NEXT_SPR) { if ((Component as any).__NEXT_SPR) {
let status: any let status: any
// pathname should have leading slash // pathname should have leading slash
let { pathname } = parse(ctx.asPath || ctx.pathname) let { pathname } = parse(ctx.asPath || ctx.pathname)
pathname = !pathname || pathname === '/' ? '/index' : pathname pathname = !pathname || pathname === '/' ? '/index' : pathname
props = await fetch( return fetch(
// @ts-ignore __NEXT_DATA__ // @ts-ignore __NEXT_DATA__
`/_next/data/${__NEXT_DATA__.buildId}${pathname}.json` `/_next/data/${__NEXT_DATA__.buildId}${pathname}.json`
) )
...@@ -658,28 +675,14 @@ export default class Router implements BaseRouter { ...@@ -658,28 +675,14 @@ export default class Router implements BaseRouter {
window.location.href = pathname! window.location.href = pathname!
return new Promise(() => {}) return new Promise(() => {})
}) })
} else { }
const AppTree = this._wrapApp(App) return loadGetInitialProps<AppContextType<Router>>(App, {
ctx.AppTree = AppTree
props = await loadGetInitialProps<AppContextType<Router>>(App, {
AppTree, AppTree,
Component, Component,
router: this, router: this,
ctx, ctx,
}) })
} })
if (cancel === this.clc) {
this.clc = null
}
if (cancelled) {
const err: any = new Error('Loading initial props cancelled')
err.cancelled = true
throw err
}
return props
} }
abortComponentLoad(as: string): void { abortComponentLoad(as: string): void {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment