Files
Andrew ClarkandGitHub 61803f818a [PPR Nav] Fix flash of loading state during back/forward (#60578)
### Depends on

- #60577 

---

A popstate navigation reads data from the local cache. It does not issue
new network requests (unless the cache entries have been evicted). So,
when navigating with back/forward, we should not switch back to the PPR
loading state. We should render the full, cached dynamic data
immediately.

To implement this, on a popstate navigation, we update the cache to drop
the prefetch data for any segment whose dynamic data was already
received. We clone the entire cache node tree and set the `prefetchRsc`
field to `null` to prevent it from being rendered. (We can't mutate the
node in place because Cache Node is a concurrent data structure.)

Technically, what we're actually checking is whether the dynamic network
response was received. But since it's a streaming response, this does
not mean that all the dynamic data has fully streamed in. It just means
that _some_ of the dynamic data was received. But as a heuristic, we
assume that the rest dynamic data will stream in quickly, so it's still
better to skip the prefetch state.

Closes NEXT-2084
2024-01-12 14:18:54 -05:00

48 lines
1.4 KiB
TypeScript

import 'server-only'
import { unstable_noStore } from 'next/cache'
// NOTE: I've intentionally not yet moved these helpers into a shared module, to
// avoid early abstraction. I will if/when we start using them for other tests.
// They are based on the testing patterns we use all over the React codebase, so
// I'm reasonably confident in them.
const TEST_DATA_SERVICE_URL = process.env.TEST_DATA_SERVICE_URL
const ARTIFICIAL_DELAY = 3000
async function getTestData(key: string, isStatic: boolean): Promise<string> {
const searchParams = new URLSearchParams({
key,
})
if (!TEST_DATA_SERVICE_URL) {
// If environment variable is not set, resolve automatically after a delay.
// This is so you can run the test app locally without spinning up a
// data server.
await new Promise<void>((resolve) =>
setTimeout(() => resolve(), ARTIFICIAL_DELAY)
)
if (!isStatic) {
unstable_noStore()
}
return key
}
const response = await fetch(
TEST_DATA_SERVICE_URL + '?' + searchParams.toString(),
{
cache: isStatic ? 'force-cache' : 'no-store',
}
)
const text = await response.text()
if (response.status !== 200) {
throw new Error(text)
}
return text
}
export async function getStaticTestData(key: string): Promise<string> {
return getTestData(key, true)
}
export async function getDynamicTestData(key: string): Promise<string> {
return getTestData(key, false)
}