2017-03-07 19:43:56 +01:00
|
|
|
/* global window */
|
2019-04-03 11:28:53 +02:00
|
|
|
import React from 'react'
|
2021-07-14 20:12:04 +02:00
|
|
|
import Router from '../shared/lib/router/router'
|
|
|
|
import type { NextRouter } from '../shared/lib/router/router'
|
2021-06-30 11:43:31 +02:00
|
|
|
import { RouterContext } from '../shared/lib/router-context'
|
2021-09-16 18:06:57 +02:00
|
|
|
import isError from '../lib/is-error'
|
2016-12-19 15:40:26 +01:00
|
|
|
|
2019-04-26 09:37:57 +02:00
|
|
|
type SingletonRouterBase = {
|
2019-04-16 06:00:48 +02:00
|
|
|
router: Router | null
|
|
|
|
readyCallbacks: Array<() => any>
|
2019-05-29 13:57:26 +02:00
|
|
|
ready(cb: () => any): void
|
2019-04-16 06:00:48 +02:00
|
|
|
}
|
|
|
|
|
2021-07-14 20:12:04 +02:00
|
|
|
export { Router }
|
|
|
|
|
|
|
|
export type { NextRouter }
|
2019-04-29 18:47:40 +02:00
|
|
|
|
2019-07-11 19:35:39 +02:00
|
|
|
export type SingletonRouter = SingletonRouterBase & NextRouter
|
2019-04-16 06:00:48 +02:00
|
|
|
|
2019-04-26 09:37:57 +02:00
|
|
|
const singletonRouter: SingletonRouterBase = {
|
2016-12-31 02:15:22 +01:00
|
|
|
router: null, // holds the actual router instance
|
|
|
|
readyCallbacks: [],
|
2019-04-16 06:00:48 +02:00
|
|
|
ready(cb: () => void) {
|
2016-12-31 02:15:22 +01:00
|
|
|
if (this.router) return cb()
|
|
|
|
if (typeof window !== 'undefined') {
|
|
|
|
this.readyCallbacks.push(cb)
|
|
|
|
}
|
2019-04-16 06:00:48 +02:00
|
|
|
},
|
2016-12-31 02:15:22 +01:00
|
|
|
}
|
2016-12-19 15:40:26 +01:00
|
|
|
|
2019-04-26 09:37:57 +02:00
|
|
|
// Create public properties and methods of the router in the singletonRouter
|
2020-02-15 19:01:10 +01:00
|
|
|
const urlPropertyFields = [
|
|
|
|
'pathname',
|
|
|
|
'route',
|
|
|
|
'query',
|
|
|
|
'asPath',
|
|
|
|
'components',
|
|
|
|
'isFallback',
|
2020-04-14 09:50:39 +02:00
|
|
|
'basePath',
|
2020-10-07 23:11:01 +02:00
|
|
|
'locale',
|
|
|
|
'locales',
|
2020-10-08 13:12:17 +02:00
|
|
|
'defaultLocale',
|
2020-12-31 17:54:32 +01:00
|
|
|
'isReady',
|
2021-02-18 19:34:33 +01:00
|
|
|
'isPreview',
|
2021-02-11 11:18:24 +01:00
|
|
|
'isLocaleDomain',
|
2021-06-22 18:55:52 +02:00
|
|
|
'domainLocales',
|
2020-02-15 19:01:10 +01:00
|
|
|
]
|
2019-05-29 13:57:26 +02:00
|
|
|
const routerEvents = [
|
|
|
|
'routeChangeStart',
|
|
|
|
'beforeHistoryChange',
|
|
|
|
'routeChangeComplete',
|
|
|
|
'routeChangeError',
|
|
|
|
'hashChangeStart',
|
|
|
|
'hashChangeComplete',
|
2021-06-22 20:43:09 +02:00
|
|
|
] as const
|
|
|
|
export type RouterEvent = typeof routerEvents[number]
|
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
const coreMethodFields = [
|
|
|
|
'push',
|
|
|
|
'replace',
|
|
|
|
'reload',
|
|
|
|
'back',
|
|
|
|
'prefetch',
|
|
|
|
'beforePopState',
|
|
|
|
]
|
2016-12-19 15:40:26 +01:00
|
|
|
|
2018-07-31 21:04:14 +02:00
|
|
|
// Events is a static property on the router, the router doesn't have to be initialized to use it
|
2019-04-26 09:37:57 +02:00
|
|
|
Object.defineProperty(singletonRouter, 'events', {
|
2019-04-16 06:00:48 +02:00
|
|
|
get() {
|
|
|
|
return Router.events
|
|
|
|
},
|
2018-07-31 21:04:14 +02:00
|
|
|
})
|
|
|
|
|
2022-08-15 16:29:51 +02:00
|
|
|
function getRouter(): Router {
|
|
|
|
if (!singletonRouter.router) {
|
|
|
|
const message =
|
|
|
|
'No router instance found.\n' +
|
|
|
|
'You should only use "next/router" on the client side of your app.\n'
|
|
|
|
throw new Error(message)
|
|
|
|
}
|
|
|
|
return singletonRouter.router
|
|
|
|
}
|
|
|
|
|
2021-01-05 16:11:37 +01:00
|
|
|
urlPropertyFields.forEach((field: string) => {
|
2021-06-11 11:51:52 +02:00
|
|
|
// Here we need to use Object.defineProperty because we need to return
|
2016-12-19 15:40:26 +01:00
|
|
|
// the property assigned to the actual router
|
|
|
|
// The value might get changed as we change routes and this is the
|
|
|
|
// proper way to access it
|
2019-04-26 09:37:57 +02:00
|
|
|
Object.defineProperty(singletonRouter, field, {
|
2019-04-16 06:00:48 +02:00
|
|
|
get() {
|
|
|
|
const router = getRouter() as any
|
|
|
|
return router[field] as string
|
|
|
|
},
|
2016-12-19 15:40:26 +01:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2021-01-05 16:11:37 +01:00
|
|
|
coreMethodFields.forEach((field: string) => {
|
2019-04-16 06:00:48 +02:00
|
|
|
// We don't really know the types here, so we add them later instead
|
2019-05-29 13:57:26 +02:00
|
|
|
;(singletonRouter as any)[field] = (...args: any[]) => {
|
2019-04-16 06:00:48 +02:00
|
|
|
const router = getRouter() as any
|
|
|
|
return router[field](...args)
|
2016-12-19 15:40:26 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2021-06-22 20:43:09 +02:00
|
|
|
routerEvents.forEach((event) => {
|
2019-04-26 09:37:57 +02:00
|
|
|
singletonRouter.ready(() => {
|
2019-04-16 06:00:48 +02:00
|
|
|
Router.events.on(event, (...args) => {
|
2019-05-29 13:57:26 +02:00
|
|
|
const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(
|
|
|
|
1
|
|
|
|
)}`
|
2019-04-26 09:37:57 +02:00
|
|
|
const _singletonRouter = singletonRouter as any
|
|
|
|
if (_singletonRouter[eventField]) {
|
2017-07-27 15:50:39 +02:00
|
|
|
try {
|
2019-04-26 09:37:57 +02:00
|
|
|
_singletonRouter[eventField](...args)
|
2017-07-27 15:50:39 +02:00
|
|
|
} catch (err) {
|
|
|
|
console.error(`Error when running the Router event: ${eventField}`)
|
2021-09-16 18:06:57 +02:00
|
|
|
console.error(
|
|
|
|
isError(err) ? `${err.message}\n${err.stack}` : err + ''
|
|
|
|
)
|
2017-07-27 15:50:39 +02:00
|
|
|
}
|
2016-12-31 02:15:22 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2019-04-26 09:37:57 +02:00
|
|
|
// Export the singletonRouter and this is the public API.
|
|
|
|
export default singletonRouter as SingletonRouter
|
2016-12-20 18:27:43 +01:00
|
|
|
|
2017-08-30 16:07:12 +02:00
|
|
|
// Reexport the withRoute HOC
|
2019-07-25 15:58:24 +02:00
|
|
|
export { default as withRouter } from './with-router'
|
2017-08-30 16:07:12 +02:00
|
|
|
|
`next/compat/router` (#42502)
After speaking with @timneutkens, this PR provides a smoother experience to users trying to migrate over to app without affecting users in pages.
This PR adds a new export available from `next/compat/router` that exposes a `useRouter()` hook that can be used in both `app/` and `pages/`. It differs from `next/router` in that it does not throw an error when the pages router is not mounted, and instead has a return type of `NextRouter | null`. This allows developers to convert components to support running in both `app/` and `pages/` as they are transitioning over to `app/`.
A component that before looked like this:
```tsx
import { useRouter } from 'next/router';
const MyComponent = () => {
const { isReady, query } = useRouter();
// ...
};
```
Will error when converted over to `next/compat/router`, as `null` cannot be destructured. Instead, developers will be able to take advantage of new hooks:
```tsx
import { useEffect } from 'react';
import { useRouter } from 'next/compat/router';
import { useSearchParams } from 'next/navigation';
const MyComponent = () => {
const router = useRouter() // may be null or a NextRouter instance
const searchParams = useSearchParams()
useEffect(() => {
if (router && !router.isReady) {
return
}
// In `app/`, searchParams will be ready immediately with the values, in
// `pages/` it will be available after the router is ready.
const search = searchParams.get('search')
// ...
}, [router, searchParams])
// ...
}
```
This component will now work in both `pages/` and `app/`. When the component is no longer used in `pages/`, you can remove the references to the compat router:
```tsx
import { useSearchParams } from 'next/navigation';
const MyComponent = () => {
const searchParams = useSearchParams()
// As this component is only used in `app/`, the compat router can be removed.
const search = searchParams.get('search')
// ...
}
```
Note that as of Next.js 13, calling `useRouter` from `next/router` will throw an error when not mounted. This now includes an error page that can be used to assist developers.
We hope to introduce a codemod that can convert instances of your `useRouter` from `next/router` to `next/compat/router` in the future.
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-11-07 19:16:28 +01:00
|
|
|
export function useRouter(): NextRouter {
|
2022-11-01 04:13:27 +01:00
|
|
|
const router = React.useContext(RouterContext)
|
`next/compat/router` (#42502)
After speaking with @timneutkens, this PR provides a smoother experience to users trying to migrate over to app without affecting users in pages.
This PR adds a new export available from `next/compat/router` that exposes a `useRouter()` hook that can be used in both `app/` and `pages/`. It differs from `next/router` in that it does not throw an error when the pages router is not mounted, and instead has a return type of `NextRouter | null`. This allows developers to convert components to support running in both `app/` and `pages/` as they are transitioning over to `app/`.
A component that before looked like this:
```tsx
import { useRouter } from 'next/router';
const MyComponent = () => {
const { isReady, query } = useRouter();
// ...
};
```
Will error when converted over to `next/compat/router`, as `null` cannot be destructured. Instead, developers will be able to take advantage of new hooks:
```tsx
import { useEffect } from 'react';
import { useRouter } from 'next/compat/router';
import { useSearchParams } from 'next/navigation';
const MyComponent = () => {
const router = useRouter() // may be null or a NextRouter instance
const searchParams = useSearchParams()
useEffect(() => {
if (router && !router.isReady) {
return
}
// In `app/`, searchParams will be ready immediately with the values, in
// `pages/` it will be available after the router is ready.
const search = searchParams.get('search')
// ...
}, [router, searchParams])
// ...
}
```
This component will now work in both `pages/` and `app/`. When the component is no longer used in `pages/`, you can remove the references to the compat router:
```tsx
import { useSearchParams } from 'next/navigation';
const MyComponent = () => {
const searchParams = useSearchParams()
// As this component is only used in `app/`, the compat router can be removed.
const search = searchParams.get('search')
// ...
}
```
Note that as of Next.js 13, calling `useRouter` from `next/router` will throw an error when not mounted. This now includes an error page that can be used to assist developers.
We hope to introduce a codemod that can convert instances of your `useRouter` from `next/router` to `next/compat/router` in the future.
Co-authored-by: JJ Kasper <22380829+ijjk@users.noreply.github.com>
2022-11-07 19:16:28 +01:00
|
|
|
if (!router) {
|
|
|
|
throw new Error(
|
|
|
|
'Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted'
|
|
|
|
)
|
2022-11-01 04:13:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return router
|
2019-04-03 11:28:53 +02:00
|
|
|
}
|
|
|
|
|
2016-12-20 18:27:43 +01:00
|
|
|
// INTERNAL APIS
|
|
|
|
// -------------
|
|
|
|
// (do not use following exports inside the app)
|
|
|
|
|
2022-07-20 18:48:45 +02:00
|
|
|
/**
|
|
|
|
* Create a router and assign it as the singleton instance.
|
|
|
|
* This is used in client side when we are initializing the app.
|
|
|
|
* This should **not** be used inside the server.
|
|
|
|
* @internal
|
|
|
|
*/
|
|
|
|
export function createRouter(
|
|
|
|
...args: ConstructorParameters<typeof Router>
|
|
|
|
): Router {
|
2019-04-26 09:37:57 +02:00
|
|
|
singletonRouter.router = new Router(...args)
|
2020-05-18 21:24:37 +02:00
|
|
|
singletonRouter.readyCallbacks.forEach((cb) => cb())
|
2019-04-26 09:37:57 +02:00
|
|
|
singletonRouter.readyCallbacks = []
|
2016-12-31 02:15:22 +01:00
|
|
|
|
2019-04-26 09:37:57 +02:00
|
|
|
return singletonRouter.router
|
2016-12-19 15:40:26 +01:00
|
|
|
}
|
|
|
|
|
2022-07-20 18:48:45 +02:00
|
|
|
/**
|
|
|
|
* This function is used to create the `withRouter` router instance
|
|
|
|
* @internal
|
|
|
|
*/
|
2019-07-11 19:35:39 +02:00
|
|
|
export function makePublicRouterInstance(router: Router): NextRouter {
|
2021-09-16 16:11:30 +02:00
|
|
|
const scopedRouter = router as any
|
2019-04-16 06:00:48 +02:00
|
|
|
const instance = {} as any
|
2017-08-30 16:07:12 +02:00
|
|
|
|
2018-06-05 17:10:28 +02:00
|
|
|
for (const property of urlPropertyFields) {
|
2021-09-16 16:11:30 +02:00
|
|
|
if (typeof scopedRouter[property] === 'object') {
|
2020-10-07 23:11:01 +02:00
|
|
|
instance[property] = Object.assign(
|
2021-09-16 16:11:30 +02:00
|
|
|
Array.isArray(scopedRouter[property]) ? [] : {},
|
|
|
|
scopedRouter[property]
|
2020-10-07 23:11:01 +02:00
|
|
|
) // makes sure query is not stateful
|
2018-06-05 17:10:28 +02:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-09-16 16:11:30 +02:00
|
|
|
instance[property] = scopedRouter[property]
|
2018-06-05 17:10:28 +02:00
|
|
|
}
|
|
|
|
|
2018-07-31 21:04:14 +02:00
|
|
|
// Events is a static property on the router, the router doesn't have to be initialized to use it
|
2019-04-16 06:00:48 +02:00
|
|
|
instance.events = Router.events
|
2018-07-31 21:04:14 +02:00
|
|
|
|
2020-05-18 21:24:37 +02:00
|
|
|
coreMethodFields.forEach((field) => {
|
2019-04-16 06:00:48 +02:00
|
|
|
instance[field] = (...args: any[]) => {
|
2021-09-16 16:11:30 +02:00
|
|
|
return scopedRouter[field](...args)
|
2017-08-30 16:07:12 +02:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return instance
|
|
|
|
}
|