Unverified Commit 24b2ff16 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

remove optimistic navigation behavior when prefetch is false (#58413)

### What?
When navigating between pages (via `prefetch: false`) within a dynamic
segment, the shared layout is re-rendered. This can cause unexpected
behavior like layout data changing when navigating between child
segments.

### Why?
When prefetch is false, we're currently opting into an "optimistic
navigation" codepath, which will optimistically render layout-routers up
to the point where data is missing, while kicking off data fetches. It
attempts to determine where refetching needs to happen by traversing the
router cache nodes and checking where data is missing. However, it
locates these cache nodes by using "segments" obtained by
[deconstructing the
URL](https://github.com/vercel/next.js/blob/fix/optimistic-bailout/packages/next/src/client/components/router-reducer/reducers/navigate-reducer.ts#L142),
which won't accurately contain dynamic segment data. For ex, `/en` which
corresponds with `/app/[lang]/page.tsx` will have a cache node key of
`lang|en|d`, not `en`. Similarly, the optimistic tree that gets
constructed will also be incorrect, since it uses the URL segment.

### How?
My initial fix was to match the dynamic segment against the segment
constructed by the URL. But after discussion with @sebmarkbage and the
team, it seems more correct to remove the optimistic case all together
as there's no guarantee that the url will actually match to that
segment.

Fixes #50670

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 8d4f4fcd
...@@ -204,7 +204,7 @@ function useChangeByServerResponse( ...@@ -204,7 +204,7 @@ function useChangeByServerResponse(
function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate { function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
return useCallback( return useCallback(
(href, navigateType, forceOptimisticNavigation, shouldScroll) => { (href, navigateType, shouldScroll) => {
const url = new URL(addBasePath(href), location.href) const url = new URL(addBasePath(href), location.href)
return dispatch({ return dispatch({
...@@ -212,7 +212,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate { ...@@ -212,7 +212,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
url, url,
isExternalUrl: isExternalURL(url), isExternalUrl: isExternalURL(url),
locationSearch: location.search, locationSearch: location.search,
forceOptimisticNavigation,
shouldScroll: shouldScroll ?? true, shouldScroll: shouldScroll ?? true,
navigateType, navigateType,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
...@@ -330,22 +329,12 @@ function Router({ ...@@ -330,22 +329,12 @@ function Router({
}, },
replace: (href, options = {}) => { replace: (href, options = {}) => {
startTransition(() => { startTransition(() => {
navigate( navigate(href, 'replace', options.scroll ?? true)
href,
'replace',
Boolean(options.forceOptimisticNavigation),
options.scroll ?? true
)
}) })
}, },
push: (href, options = {}) => { push: (href, options = {}) => {
startTransition(() => { startTransition(() => {
navigate( navigate(href, 'push', options.scroll ?? true)
href,
'push',
Boolean(options.forceOptimisticNavigation),
options.scroll ?? true
)
}) })
}, },
refresh: () => { refresh: () => {
......
import { createOptimisticTree } from './create-optimistic-tree'
import type { FlightRouterState } from '../../../server/app-render/types'
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
undefined,
undefined,
true,
]
describe('createOptimisticTree', () => {
it('should create an optimistic tree', () => {
const initialRouterStateTree = getInitialRouterStateTree()
const pathname = '/dashboard/settings'
const segments = pathname.split('/')
// TODO-APP: figure out something better for index pages
segments.push('')
const result = createOptimisticTree(segments, initialRouterStateTree, false)
expect(result).toMatchObject([
'',
{
children: [
'dashboard',
{
children: [
'settings',
{
children: ['', {}],
},
],
},
undefined,
'refetch',
],
},
undefined,
undefined,
true,
])
})
})
import type { FlightRouterState } from '../../../server/app-render/types'
import { matchSegment } from '../match-segments'
/**
* Create optimistic version of router state based on the existing router state and segments.
* This is used to allow rendering layout-routers up till the point where data is missing.
*/
export function createOptimisticTree(
segments: string[],
flightRouterState: FlightRouterState | null,
parentRefetch: boolean
): FlightRouterState {
const [existingSegment, existingParallelRoutes, url, refresh, isRootLayout] =
flightRouterState || [null, {}]
const segment = segments[0]
const isLastSegment = segments.length === 1
const segmentMatches =
existingSegment !== null && matchSegment(existingSegment, segment)
// if there are multiple parallel routes at this level, we need to refetch here
// to ensure we get the correct tree. This is because we don't know which
// parallel route will match the next segment.
const hasMultipleParallelRoutes =
Object.keys(existingParallelRoutes).length > 1
const shouldRefetchThisLevel =
!flightRouterState || !segmentMatches || hasMultipleParallelRoutes
let parallelRoutes: FlightRouterState[1] = {}
if (existingSegment !== null && segmentMatches) {
parallelRoutes = existingParallelRoutes
}
let childTree
// if there's multiple parallel routes at this level, we shouldn't create an
// optimistic tree for the next level because we don't know which one will
// match the next segment.
if (!isLastSegment && !hasMultipleParallelRoutes) {
const childItem = createOptimisticTree(
segments.slice(1),
parallelRoutes ? parallelRoutes.children : null,
parentRefetch || shouldRefetchThisLevel
)
childTree = childItem
}
const result: FlightRouterState = [
segment,
{
...parallelRoutes,
...(childTree ? { children: childTree } : {}),
},
]
if (url) {
result[2] = url
}
if (!parentRefetch && shouldRefetchThisLevel) {
result[3] = 'refetch'
} else if (segmentMatches && refresh) {
result[3] = refresh
}
if (segmentMatches && isRootLayout) {
result[4] = isRootLayout
}
return result
}
...@@ -11,9 +11,8 @@ export function fillCacheWithDataProperty( ...@@ -11,9 +11,8 @@ export function fillCacheWithDataProperty(
newCache: CacheNode, newCache: CacheNode,
existingCache: CacheNode, existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath, flightSegmentPath: FlightSegmentPath,
fetchResponse: () => Promise<FetchServerResponseResult>, fetchResponse: () => Promise<FetchServerResponseResult>
bailOnParallelRoutes: boolean = false ): void {
): { bailOptimistic: boolean } | undefined {
const isLastEntry = flightSegmentPath.length <= 2 const isLastEntry = flightSegmentPath.length <= 2
const [parallelRouteKey, segment] = flightSegmentPath const [parallelRouteKey, segment] = flightSegmentPath
...@@ -22,16 +21,6 @@ export function fillCacheWithDataProperty( ...@@ -22,16 +21,6 @@ export function fillCacheWithDataProperty(
const existingChildSegmentMap = const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey) existingCache.parallelRoutes.get(parallelRouteKey)
if (
!existingChildSegmentMap ||
(bailOnParallelRoutes && existingCache.parallelRoutes.size > 1)
) {
// Bailout because the existing cache does not have the path to the leaf node
// or the existing cache has multiple parallel routes
// Will trigger lazy fetch in layout-router because of missing segment
return { bailOptimistic: true }
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey) let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) { if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
...@@ -39,7 +28,7 @@ export function fillCacheWithDataProperty( ...@@ -39,7 +28,7 @@ export function fillCacheWithDataProperty(
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap) newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
} }
const existingChildCacheNode = existingChildSegmentMap.get(cacheKey) const existingChildCacheNode = existingChildSegmentMap?.get(cacheKey)
let childCacheNode = childSegmentMap.get(cacheKey) let childCacheNode = childSegmentMap.get(cacheKey)
// In case of last segment start off the fetch at this level and don't copy further down. // In case of last segment start off the fetch at this level and don't copy further down.
......
...@@ -183,7 +183,6 @@ describe('navigateReducer', () => { ...@@ -183,7 +183,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -398,7 +397,6 @@ describe('navigateReducer', () => { ...@@ -398,7 +397,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -594,7 +592,6 @@ describe('navigateReducer', () => { ...@@ -594,7 +592,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -754,7 +751,6 @@ describe('navigateReducer', () => { ...@@ -754,7 +751,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'replace', navigateType: 'replace',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -841,176 +837,6 @@ describe('navigateReducer', () => { ...@@ -841,176 +837,6 @@ describe('navigateReducer', () => {
`) `)
}) })
it('should apply navigation for forceOptimisticNavigation', async () => {
const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking'
const children = (
<html>
<head></head>
<body>Root layout</body>
</html>
)
const initialParallelRoutes: CacheNode['parallelRoutes'] = new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'__PAGE__',
{
status: CacheStates.READY,
data: null,
subTreeData: <>Linking page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
data: null,
subTreeData: <>Linking layout level</>,
},
],
]),
],
])
const state = createInitialRouterState({
buildId,
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
})
const state2 = createInitialRouterState({
buildId,
initialTree,
initialHead: null,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
})
const action: NavigateAction = {
type: ACTION_NAVIGATE,
url: new URL('/linking/about', 'https://localhost'),
isExternalUrl: false,
locationSearch: '',
navigateType: 'push',
shouldScroll: true,
forceOptimisticNavigation: true,
cache: {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
const newState = await runPromiseThrowChain(() =>
navigateReducer(state2, action)
)
expect(newState).toMatchInlineSnapshot(`
{
"buildId": "development",
"cache": {
"data": null,
"parallelRoutes": Map {
"children" => Map {
"linking" => {
"data": null,
"parallelRoutes": Map {
"children" => Map {
"__PAGE__" => {
"data": null,
"parallelRoutes": Map {},
"status": "READY",
"subTreeData": <React.Fragment>
Linking page
</React.Fragment>,
},
"about" => {
"data": Promise {},
"parallelRoutes": Map {},
"status": "DATAFETCH",
"subTreeData": null,
},
},
},
"status": "READY",
"subTreeData": <React.Fragment>
Linking layout level
</React.Fragment>,
},
},
},
"status": "READY",
"subTreeData": <html>
<head />
<body>
Root layout
</body>
</html>,
},
"canonicalUrl": "/linking/about",
"focusAndScrollRef": {
"apply": true,
"hashFragment": null,
"onlyHashChange": false,
"segmentPaths": [],
},
"nextUrl": "/linking/about",
"prefetchCache": Map {},
"pushRef": {
"mpaNavigation": false,
"pendingPush": true,
"preserveCustomHistoryState": false,
},
"tree": [
"",
{
"children": [
"linking",
{
"children": [
"about",
{
"children": [
"__PAGE__",
{},
],
},
,
"refetch",
],
},
],
},
,
,
true,
],
}
`)
})
it('should apply navigation for scroll', async () => { it('should apply navigation for scroll', async () => {
const initialTree = getInitialRouterStateTree() const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking' const initialCanonicalUrl = '/linking'
...@@ -1081,7 +907,6 @@ describe('navigateReducer', () => { ...@@ -1081,7 +907,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: false, // should not scroll shouldScroll: false, // should not scroll
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -1252,7 +1077,6 @@ describe('navigateReducer', () => { ...@@ -1252,7 +1077,6 @@ describe('navigateReducer', () => {
navigateType: 'push', navigateType: 'push',
locationSearch: '', locationSearch: '',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -1536,7 +1360,6 @@ describe('navigateReducer', () => { ...@@ -1536,7 +1360,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -1742,7 +1565,6 @@ describe('navigateReducer', () => { ...@@ -1742,7 +1565,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
...@@ -1892,7 +1714,6 @@ describe('navigateReducer', () => { ...@@ -1892,7 +1714,6 @@ describe('navigateReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
......
...@@ -9,7 +9,6 @@ import type { FetchServerResponseResult } from '../fetch-server-response' ...@@ -9,7 +9,6 @@ import type { FetchServerResponseResult } from '../fetch-server-response'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath' import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { fillCacheWithDataProperty } from '../fill-cache-with-data-property' import { fillCacheWithDataProperty } from '../fill-cache-with-data-property'
import { createOptimisticTree } from '../create-optimistic-tree'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { shouldHardNavigate } from '../should-hard-navigate' import { shouldHardNavigate } from '../should-hard-navigate'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
...@@ -88,15 +87,9 @@ function addRefetchToLeafSegments( ...@@ -88,15 +87,9 @@ function addRefetchToLeafSegments(
) )
for (const segmentPaths of segmentPathsToFill) { for (const segmentPaths of segmentPathsToFill) {
const res = fillCacheWithDataProperty( fillCacheWithDataProperty(newCache, currentCache, segmentPaths, data)
newCache,
currentCache, appliedPatch = true
segmentPaths,
data
)
if (!res?.bailOptimistic) {
appliedPatch = true
}
} }
return appliedPatch return appliedPatch
...@@ -105,16 +98,9 @@ export function navigateReducer( ...@@ -105,16 +98,9 @@ export function navigateReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: NavigateAction action: NavigateAction
): ReducerState { ): ReducerState {
const { const { url, isExternalUrl, navigateType, cache, mutable, shouldScroll } =
url, action
isExternalUrl, const { hash } = url
navigateType,
cache,
mutable,
forceOptimisticNavigation,
shouldScroll,
} = action
const { pathname, hash } = url
const href = createHrefFromUrl(url) const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push' const pendingPush = navigateType === 'push'
// we want to prune the prefetch cache on every navigation to avoid it growing too large // we want to prune the prefetch cache on every navigation to avoid it growing too large
...@@ -135,84 +121,6 @@ export function navigateReducer( ...@@ -135,84 +121,6 @@ export function navigateReducer(
let prefetchValues = state.prefetchCache.get(createHrefFromUrl(url, false)) let prefetchValues = state.prefetchCache.get(createHrefFromUrl(url, false))
if (
forceOptimisticNavigation &&
prefetchValues?.kind !== PrefetchKind.TEMPORARY
) {
const segments = pathname.split('/')
// TODO-APP: figure out something better for index pages
segments.push('__PAGE__')
// Optimistic tree case.
// If the optimistic tree is deeper than the current state leave that deeper part out of the fetch
const optimisticTree = createOptimisticTree(segments, state.tree, false)
// we need a copy of the cache in case we need to revert to it
const temporaryCacheNode: CacheNode = {
...cache,
}
// Copy subTreeData for the root node of the cache.
// Note: didn't do it above because typescript doesn't like it.
temporaryCacheNode.status = CacheStates.READY
temporaryCacheNode.subTreeData = state.cache.subTreeData
temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes)
let data: Promise<FetchServerResponseResult> | null = null
const fetchResponse = () => {
if (!data) {
data = fetchServerResponse(
url,
optimisticTree,
state.nextUrl,
state.buildId
)
}
return data
}
// TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether.
// TODO-APP: re-evaluate if we need to strip the last segment
const optimisticFlightSegmentPath = segments
.slice(1)
.map((segment) => ['children', segment])
.flat()
// Copy existing cache nodes as far as possible and fill in `data` property with the started data fetch.
// The `data` property is used to suspend in layout-router during render if it hasn't resolved yet by the time it renders.
const res = fillCacheWithDataProperty(
temporaryCacheNode,
state.cache,
optimisticFlightSegmentPath,
fetchResponse,
true
)
// If optimistic fetch couldn't happen it falls back to the non-optimistic case.
if (!res?.bailOptimistic) {
mutable.previousTree = state.tree
mutable.patchedTree = optimisticTree
mutable.pendingPush = pendingPush
mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll
mutable.scrollableSegments = []
mutable.cache = temporaryCacheNode
mutable.canonicalUrl = href
state.prefetchCache.set(createHrefFromUrl(url, false), {
data: data ? data : null,
// this will make sure that the entry will be discarded after 30s
kind: PrefetchKind.TEMPORARY,
prefetchTime: Date.now(),
treeAtTimeOfPrefetch: state.tree,
lastUsedTime: Date.now(),
})
return handleMutable(state, mutable)
}
}
// If we don't have a prefetch value, we need to create one // If we don't have a prefetch value, we need to create one
if (!prefetchValues) { if (!prefetchValues) {
const data = fetchServerResponse( const data = fetchServerResponse(
......
...@@ -502,7 +502,6 @@ describe('serverPatchReducer', () => { ...@@ -502,7 +502,6 @@ describe('serverPatchReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
forceOptimisticNavigation: false,
cache: { cache: {
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
......
...@@ -23,7 +23,6 @@ export type RouterChangeByServerResponse = ( ...@@ -23,7 +23,6 @@ export type RouterChangeByServerResponse = (
export type RouterNavigate = ( export type RouterNavigate = (
href: string, href: string,
navigateType: 'push' | 'replace', navigateType: 'push' | 'replace',
forceOptimisticNavigation: boolean,
shouldScroll: boolean shouldScroll: boolean
) => void ) => void
...@@ -102,11 +101,6 @@ export interface ServerActionAction { ...@@ -102,11 +101,6 @@ export interface ServerActionAction {
* - The cache is reused * - The cache is reused
* - If any cache nodes are missing they'll be fetched in layout-router and trigger the SERVER_PATCH action * - If any cache nodes are missing they'll be fetched in layout-router and trigger the SERVER_PATCH action
* - page was not prefetched * - page was not prefetched
* - The navigate was called from `next/link` with `prefetch={false}`. This case is called `forceOptimisticNavigation`. It triggers an optimistic navigation so that loading spinners can be shown early if any.
* - Creates an optimistic router tree based on the provided url
* - Adds a cache node to the cache with a Flight data fetch that was eagerly started in the reducer
* - Flight data fetch is suspended in the layout-router
* - Triggers SERVER_PATCH action when the data comes back, this will apply the data to the cache and router state, at that point the optimistic router tree is replaced by the actual router tree.
* - The navigate was called from `next/router` (`router.push()` / `router.replace()`) / `next/link` without prefetched data available (e.g. the prefetch didn't come back from the server before clicking the link) * - The navigate was called from `next/router` (`router.push()` / `router.replace()`) / `next/link` without prefetched data available (e.g. the prefetch didn't come back from the server before clicking the link)
* - Flight data is fetched in the reducer (suspends the reducer) * - Flight data is fetched in the reducer (suspends the reducer)
* - Router state tree is created based on Flight data * - Router state tree is created based on Flight data
...@@ -123,7 +117,6 @@ export interface NavigateAction { ...@@ -123,7 +117,6 @@ export interface NavigateAction {
isExternalUrl: boolean isExternalUrl: boolean
locationSearch: Location['search'] locationSearch: Location['search']
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
forceOptimisticNavigation: boolean
shouldScroll: boolean shouldScroll: boolean
cache: CacheNode cache: CacheNode
mutable: Mutable mutable: Mutable
......
...@@ -199,8 +199,7 @@ function linkClicked( ...@@ -199,8 +199,7 @@ function linkClicked(
shallow?: boolean, shallow?: boolean,
scroll?: boolean, scroll?: boolean,
locale?: string | false, locale?: string | false,
isAppRouter?: boolean, isAppRouter?: boolean
prefetchEnabled?: boolean
): void { ): void {
const { nodeName } = e.currentTarget const { nodeName } = e.currentTarget
...@@ -230,7 +229,6 @@ function linkClicked( ...@@ -230,7 +229,6 @@ function linkClicked(
}) })
} else { } else {
router[replace ? 'replace' : 'push'](as || href, { router[replace ? 'replace' : 'push'](as || href, {
forceOptimisticNavigation: !prefetchEnabled,
scroll: routerScroll, scroll: routerScroll,
}) })
} }
...@@ -634,8 +632,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -634,8 +632,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
shallow, shallow,
scroll, scroll,
locale, locale,
isAppRouter, isAppRouter
prefetchEnabled
) )
}, },
onMouseEnter(e) { onMouseEnter(e) {
......
...@@ -69,7 +69,6 @@ export type CacheNode = ...@@ -69,7 +69,6 @@ export type CacheNode =
export interface NavigateOptions { export interface NavigateOptions {
/** @internal */ /** @internal */
forceOptimisticNavigation?: boolean
scroll?: boolean scroll?: boolean
} }
......
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-prefetch-false-loading',
{
files: __dirname,
},
({ next }) => {
it('should render loading for the inital render', async () => {
const $ = await next.render$('/en/testing')
expect($('#loading').text()).toBe('Loading...')
})
it('should not re-trigger loading state when navigating between pages that share a dynamic layout', async () => {
const logStartIndex = next.cliOutput.length
const browser = await next.browser('/en/testing')
let initialRandomNumber = await browser
.elementById('random-number')
.text()
await browser.elementByCss('[href="/en/testing/test"]').click()
expect(await browser.hasElementByCssSelector('#loading')).toBeFalsy()
await check(
() => browser.hasElementByCssSelector('#nested-testing-page'),
true
)
const newRandomNumber = await browser.elementById('random-number').text()
expect(initialRandomNumber).toBe(newRandomNumber)
await check(() => {
const logOccurrences =
next.cliOutput.slice(logStartIndex).split('re-fetching in layout')
.length - 1
return logOccurrences
}, 1)
})
}
)
import React from 'react'
export default async function Root({
children,
}: {
children: React.ReactNode
}) {
console.log('re-fetching in layout')
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
// ensure that we never show a cached value here to validate
// that navigating between segments is not refreshing the value
{ cache: 'no-store' }
)
const randomNumber = await data.text()
return (
<div>
<p id="random-number">{randomNumber}</p>
{children}
</div>
)
}
'use client'
import React from 'react'
import Link from 'next/link'
export default function IndexPage() {
return (
<div>
On client
<Link href={'/en/testing/test'} prefetch={false}>
To /en/testing/test
</Link>
</div>
)
}
import React from 'react'
export default async function Root({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
Nested Layout
{children}
</div>
)
}
import React from 'react'
import ClientComponent from './client-component'
export default function IndexPage() {
return (
<div id="testing-page">
<p>Testing Page</p>
<ClientComponent />
</div>
)
}
'use client'
import React from 'react'
import Link from 'next/link'
export default function IndexPage() {
return (
<div>
On client
<Link href={'/en/testing'} prefetch={false}>
To /en/testing
</Link>
</div>
)
}
import React from 'react'
import ClientComponent from './client-component'
export default function IndexPage() {
return (
<div id="nested-testing-page">
<p>Testing/Test Page</p>
<ClientComponent />
</div>
)
}
import React from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html lang={'en'}>
<body>{children}</body>
</html>
)
}
import React from 'react'
export default function OuterLoading() {
return <div id="loading">Loading...</div>
}
...@@ -308,7 +308,6 @@ ...@@ -308,7 +308,6 @@
"navigateReducer should apply navigation", "navigateReducer should apply navigation",
"navigateReducer should apply navigation for external url (push)", "navigateReducer should apply navigation for external url (push)",
"navigateReducer should apply navigation for external url (replace)", "navigateReducer should apply navigation for external url (replace)",
"navigateReducer should apply navigation for forceOptimisticNavigation",
"navigateReducer should apply navigation for hash fragments within a different tree", "navigateReducer should apply navigation for hash fragments within a different tree",
"navigateReducer should apply navigation for hash fragments within the same tree", "navigateReducer should apply navigation for hash fragments within the same tree",
"navigateReducer should apply navigation for scroll", "navigateReducer should apply navigation for scroll",
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