Unverified Commit 5dcfec40 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Add refresh API to next/cache (#84666)

This provides a way to refresh the client cache from within a server
action. This is useful when you need to refresh the client UI / read
your writes without needing to rely on `updateTag`.

---------
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent e3c8a66e
---
title: refresh
description: API Reference for the refresh function.
---
`refresh` allows you to refresh the client router from within a [Server Action](/docs/app/getting-started/updating-data).
## Usage
`refresh` can **only** be called from within Server Actions. It cannot be used in Route Handlers, Client Components, or any other context.
## Parameters
```tsx
refresh(): void;
```
## Returns
`refresh` does not return a value.
## Examples
```ts filename="app/actions.ts" switcher
'use server'
import { refresh } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const title = formData.get('title')
const content = formData.get('content')
// Create the post in your database
const post = await db.post.create({
data: { title, content },
})
refresh()
}
```
```js filename="app/actions.js" switcher
'use server'
import { refresh } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData) {
const title = formData.get('title')
const content = formData.get('content')
// Create the post in your database
const post = await db.post.create({
data: { title, content },
})
refresh()
}
```
### Error when used outside Server Actions
```ts filename="app/api/posts/route.ts" switcher
import { refresh } from 'next/cache'
export async function POST() {
// This will throw an error
refresh()
}
```
...@@ -5,6 +5,7 @@ export { ...@@ -5,6 +5,7 @@ export {
revalidateTag, revalidateTag,
unstable_expirePath, unstable_expirePath,
unstable_expireTag, unstable_expireTag,
refresh,
} from 'next/dist/server/web/spec-extension/revalidate' } from 'next/dist/server/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store' export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
......
...@@ -12,6 +12,8 @@ const cacheExports = { ...@@ -12,6 +12,8 @@ const cacheExports = {
unstable_expirePath: require('next/dist/server/web/spec-extension/revalidate') unstable_expirePath: require('next/dist/server/web/spec-extension/revalidate')
.unstable_expirePath, .unstable_expirePath,
refresh: require('next/dist/server/web/spec-extension/revalidate').refresh,
unstable_noStore: unstable_noStore:
require('next/dist/server/web/spec-extension/unstable-no-store') require('next/dist/server/web/spec-extension/unstable-no-store')
.unstable_noStore, .unstable_noStore,
...@@ -33,3 +35,4 @@ exports.unstable_expirePath = cacheExports.unstable_expirePath ...@@ -33,3 +35,4 @@ exports.unstable_expirePath = cacheExports.unstable_expirePath
exports.unstable_noStore = cacheExports.unstable_noStore exports.unstable_noStore = cacheExports.unstable_noStore
exports.unstable_cacheLife = cacheExports.unstable_cacheLife exports.unstable_cacheLife = cacheExports.unstable_cacheLife
exports.unstable_cacheTag = cacheExports.unstable_cacheTag exports.unstable_cacheTag = cacheExports.unstable_cacheTag
exports.refresh = cacheExports.refresh
...@@ -867,5 +867,6 @@ ...@@ -867,5 +867,6 @@
"866": "Both \"%s\" and \"%s\" files are detected. Please use \"%s\" instead.", "866": "Both \"%s\" and \"%s\" files are detected. Please use \"%s\" instead.",
"867": "The %s \"%s\" must export a %s or a \\`default\\` function", "867": "The %s \"%s\" must export a %s or a \\`default\\` function",
"868": "No reference found for param: %s in reference: %s", "868": "No reference found for param: %s in reference: %s",
"869": "No reference found for segment: %s with reference: %s" "869": "No reference found for segment: %s with reference: %s",
"870": "refresh can only be called from within a Server Action. See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh"
} }
...@@ -534,6 +534,7 @@ declare module 'next/cache' { ...@@ -534,6 +534,7 @@ declare module 'next/cache' {
revalidatePath, revalidatePath,
unstable_expireTag, unstable_expireTag,
unstable_expirePath, unstable_expirePath,
refresh,
} from 'next/dist/server/web/spec-extension/revalidate' } from 'next/dist/server/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store' export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
......
...@@ -55,6 +55,32 @@ export function unstable_expirePath( ...@@ -55,6 +55,32 @@ export function unstable_expirePath(
return revalidate(tags, `unstable_expirePath ${originalPath}`) return revalidate(tags, `unstable_expirePath ${originalPath}`)
} }
/**
* This function allows you to refresh client cache from server actions.
* It's useful as dynamic data can be cached on the client which won't
* be refreshed by expireTag
*/
export function refresh() {
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (
!workStore ||
workStore.page.endsWith('/route') ||
workUnitStore?.phase !== 'action'
) {
throw new Error(
'refresh can only be called from within a Server Action. ' +
'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'
)
}
if (workStore) {
// TODO: break this to it's own field
workStore.pathWasRevalidated = true
}
}
/** /**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag. * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
* *
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Loading() {
return <div id="loading">loading...</div>
}
import { connection } from 'next/server'
import { unstable_cache, refresh } from 'next/cache'
const cachedFunction = unstable_cache(async () => {
refresh()
return 'data'
}, ['test-key'])
export default async function Page() {
await connection()
const data = await cachedFunction()
return <div>{data}</div>
}
import { connection } from 'next/server'
import { refresh } from 'next/cache'
export default async function Page() {
await connection()
refresh()
return <div>This should error</div>
}
import { refresh } from 'next/cache'
import { connection } from 'next/server'
export async function GET() {
await connection()
refresh()
return new Response('ok')
}
'use server'
import { refresh } from 'next/cache'
export async function triggerRefresh() {
refresh()
}
import { triggerRefresh } from './actions'
export default function Page() {
const timestamp = performance.now()
return (
<>
<div id="server-timestamp">{timestamp}</div>
<form action={triggerRefresh}>
<button id="refresh-button" type="submit">
Refresh
</button>
</form>
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry, assertHasRedbox, getRedboxDescription } from 'next-test-utils'
describe('app-dir refresh', () => {
const { next, skipped, isNextDev } = nextTestSetup({
files: __dirname,
// We do not have access to runtime logs when deployed
skipDeployment: true,
})
if (skipped) return
it('should refresh client cache when refresh() is called in a server action', async () => {
const browser = await next.browser('/refresh')
const initialServerTimestamp = await browser
.elementById('server-timestamp')
.text()
expect(initialServerTimestamp).toBeTruthy()
await new Promise((resolve) => setTimeout(resolve, 100))
await browser.elementById('refresh-button').click()
await retry(async () => {
const newServerTimestamp = await browser
.elementById('server-timestamp')
.text()
expect(newServerTimestamp).not.toBe(initialServerTimestamp)
expect(Number(newServerTimestamp)).toBeGreaterThan(
Number(initialServerTimestamp)
)
})
})
it('should throw an error when refresh() is called during page render', async () => {
const browser = await next.browser('/refresh-invalid-render')
if (isNextDev) {
await assertHasRedbox(browser)
const description = await getRedboxDescription(browser)
expect(description).toContain(
'refresh can only be called from within a Server Action'
)
} else {
await retry(async () => {
expect(next.cliOutput).toContain(
'refresh can only be called from within a Server Action'
)
})
}
})
it('should throw an error when refresh() is called in a route handler', async () => {
const res = await next.fetch('/refresh-invalid-route')
expect(res.status).toBe(500)
await retry(async () => {
expect(next.cliOutput).toContain(
'refresh can only be called from within a Server Action'
)
})
})
it('should throw an error when refresh() is called in unstable_cache', async () => {
const browser = await next.browser('/refresh-invalid-cache')
if (isNextDev) {
await assertHasRedbox(browser)
const description = await getRedboxDescription(browser)
expect(description).toContain(
'refresh can only be called from within a Server Action'
)
} else {
await retry(async () => {
expect(next.cliOutput).toContain(
'refresh can only be called from within a Server Action'
)
})
}
})
})
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