Unverified Commit 6d5c4874 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Implement `isFallback` Router Property (#10539)

This adds a `isFallback` property to detect if the page is being rendered in "fallback" mode or normal mode.
Accessed via the `useRouter()` hook.

---

Closes #10527
parent ae9b13e0
...@@ -206,6 +206,7 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => { ...@@ -206,6 +206,7 @@ export default async ({ webpackHMR: passedWebpackHMR } = {}) => {
Component, Component,
wrapApp, wrapApp,
err: initialErr, err: initialErr,
isFallback,
subscription: ({ Component, props, err }, App) => { subscription: ({ Component, props, err }, App) => {
render({ App, Component, props, err }) render({ App, Component, props, err })
}, },
......
...@@ -29,7 +29,14 @@ const singletonRouter: SingletonRouterBase = { ...@@ -29,7 +29,14 @@ const singletonRouter: SingletonRouterBase = {
} }
// Create public properties and methods of the router in the singletonRouter // Create public properties and methods of the router in the singletonRouter
const urlPropertyFields = ['pathname', 'route', 'query', 'asPath', 'components'] const urlPropertyFields = [
'pathname',
'route',
'query',
'asPath',
'components',
'isFallback',
]
const routerEvents = [ const routerEvents = [
'routeChangeStart', 'routeChangeStart',
'beforeHistoryChange', 'beforeHistoryChange',
......
...@@ -49,6 +49,7 @@ export type NextRouter = BaseRouter & ...@@ -49,6 +49,7 @@ export type NextRouter = BaseRouter &
| 'prefetch' | 'prefetch'
| 'beforePopState' | 'beforePopState'
| 'events' | 'events'
| 'isFallback'
> >
type RouteInfo = { type RouteInfo = {
...@@ -122,6 +123,7 @@ export default class Router implements BaseRouter { ...@@ -122,6 +123,7 @@ export default class Router implements BaseRouter {
events: MittEmitter events: MittEmitter
_wrapApp: (App: ComponentType) => any _wrapApp: (App: ComponentType) => any
isSsr: boolean isSsr: boolean
isFallback: boolean
static events: MittEmitter = mitt() static events: MittEmitter = mitt()
...@@ -137,6 +139,7 @@ export default class Router implements BaseRouter { ...@@ -137,6 +139,7 @@ export default class Router implements BaseRouter {
Component, Component,
err, err,
subscription, subscription,
isFallback,
}: { }: {
subscription: Subscription subscription: Subscription
initialProps: any initialProps: any
...@@ -145,6 +148,7 @@ export default class Router implements BaseRouter { ...@@ -145,6 +148,7 @@ export default class Router implements BaseRouter {
App: ComponentType App: ComponentType
wrapApp: (App: ComponentType) => any wrapApp: (App: ComponentType) => any
err?: Error err?: Error
isFallback: boolean
} }
) { ) {
// represents the current component key // represents the current component key
...@@ -180,6 +184,8 @@ export default class Router implements BaseRouter { ...@@ -180,6 +184,8 @@ export default class Router implements BaseRouter {
// back from external site // back from external site
this.isSsr = true this.isSsr = true
this.isFallback = isFallback
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
// in order for `e.state` to work on the `onpopstate` event // in order for `e.state` to work on the `onpopstate` event
// we have to register the initial route upon initialization // we have to register the initial route upon initialization
...@@ -580,6 +586,8 @@ export default class Router implements BaseRouter { ...@@ -580,6 +586,8 @@ export default class Router implements BaseRouter {
as: string, as: string,
data: RouteInfo data: RouteInfo
): void { ): void {
this.isFallback = false
this.route = route this.route = route
this.pathname = pathname this.pathname = pathname
this.query = query this.query = query
......
...@@ -46,14 +46,22 @@ class ServerRouter implements NextRouter { ...@@ -46,14 +46,22 @@ class ServerRouter implements NextRouter {
query: ParsedUrlQuery query: ParsedUrlQuery
asPath: string asPath: string
events: any events: any
isFallback: boolean
// TODO: Remove in the next major version, as this would mean the user is adding event listeners in server-side `render` method // TODO: Remove in the next major version, as this would mean the user is adding event listeners in server-side `render` method
static events: MittEmitter = mitt() static events: MittEmitter = mitt()
constructor(pathname: string, query: ParsedUrlQuery, as: string) { constructor(
pathname: string,
query: ParsedUrlQuery,
as: string,
{ isFallback }: { isFallback: boolean }
) {
this.route = pathname.replace(/\/$/, '') || '/' this.route = pathname.replace(/\/$/, '') || '/'
this.pathname = pathname this.pathname = pathname
this.query = query this.query = query
this.asPath = as this.asPath = as
this.isFallback = isFallback
} }
push(): any { push(): any {
noRouter() noRouter()
...@@ -394,7 +402,9 @@ export async function renderToHTML( ...@@ -394,7 +402,9 @@ export async function renderToHTML(
// @ts-ignore url will always be set // @ts-ignore url will always be set
const asPath: string = req.url const asPath: string = req.url
const router = new ServerRouter(pathname, query, asPath) const router = new ServerRouter(pathname, query, asPath, {
isFallback: isFallback,
})
const ctx = { const ctx = {
err, err,
req: isAutoExport ? undefined : req, req: isAutoExport ? undefined : req,
......
import { useRouter } from 'next/router'
export async function unstable_getStaticProps({ params: { slug } }) { export async function unstable_getStaticProps({ params: { slug } }) {
if (slug[0] === 'delayby3s') {
await new Promise(resolve => setTimeout(resolve, 3000))
}
return { return {
props: { props: {
slug, slug,
...@@ -18,4 +24,10 @@ export async function unstable_getStaticPaths() { ...@@ -18,4 +24,10 @@ export async function unstable_getStaticPaths() {
} }
} }
export default ({ slug }) => <p id="catchall">Hi {slug?.join('/')}</p> export default ({ slug }) => {
const { isFallback } = useRouter()
if (isFallback) {
return <p id="catchall">fallback</p>
}
return <p id="catchall">Hi {slug.join('/')}</p>
}
...@@ -386,9 +386,20 @@ const runTests = (dev = false) => { ...@@ -386,9 +386,20 @@ const runTests = (dev = false) => {
} }
// Production will render fallback for a "lazy" route // Production will render fallback for a "lazy" route
else { else {
const browser = await webdriver(appPort, '/catchall/notreturnedinpaths') const html = await renderViaHTTP(appPort, '/catchall/notreturnedinpaths')
const text = await browser.elementByCss('#catchall').text() const $ = cheerio.load(html)
expect(text).toMatch(/Hi.*?notreturnedinpaths/) expect($('#catchall').text()).toBe('fallback')
// hydration
const browser = await webdriver(appPort, '/catchall/delayby3s')
const text1 = await browser.elementByCss('#catchall').text()
expect(text1).toBe('fallback')
await new Promise(resolve => setTimeout(resolve, 4000))
const text2 = await browser.elementByCss('#catchall').text()
expect(text2).toMatch(/Hi.*?delayby3s/)
} }
}) })
......
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