diff --git a/docs.json b/docs.json index 779cc9e..16c0f2a 100644 --- a/docs.json +++ b/docs.json @@ -121,6 +121,7 @@ "v2/data-props/partial-reloads", "v2/data-props/deferred-props", "v2/data-props/merging-props", + "v2/data-props/once-props", "v2/data-props/polling", "v2/data-props/prefetching", "v2/data-props/load-when-visible", diff --git a/v2/core-concepts/the-protocol.mdx b/v2/core-concepts/the-protocol.mdx index ac44715..98211cd 100644 --- a/v2/core-concepts/the-protocol.mdx +++ b/v2/core-concepts/the-protocol.mdx @@ -143,6 +143,10 @@ The following headers are automatically sent by Inertia when making requests. Yo Indicates whether the requested data should be appended or prepended when using [Infinite scroll](/v2/data-props/infinite-scroll). + + Comma-separated list of non-expired [once prop](/v2/data-props/once-props) keys already loaded on the client. The server will skip resolving these props unless explicitly requested via a partial reload or force refreshed server-side. + + ## Response Headers The following headers should be sent by your server-side adapter in Inertia responses. If you're using an official server-side adapter, these are handled automatically. @@ -211,6 +215,10 @@ Inertia shares data between the server and client via a page object. This object Configuration for client-side [lazy loading of props](/v2/data-props/deferred-props). + + Configuration for [once props](/v2/data-props/once-props) that should only be resolved once and reused on subsequent pages. Each entry maps a key to an object containing the `prop` name and optional `expiresAt` timestamp (in milliseconds). + + On standard full page visits, the page object is JSON encoded into the `data-page` attribute in the root `
`. On Inertia visits (as indicated by the presence of the `X-Inertia` header), the page object is returned as the JSON payload. ### Basic Page Object @@ -360,6 +368,78 @@ When using [Infinite scroll](/v2/data-props/infinite-scroll), the page object in } ``` +### Page Object with Once Props + +When using [once props](/v2/data-props/once-props), the page object includes an `onceProps` configuration. Each entry maps a key to the prop name and an optional expiration timestamp. + +```json +{ + "component": "Billing/Plans", + "props": { + "errors": {}, + "plans": [ + { + "id": 1, + "name": "Basic" + }, + { + "id": 2, + "name": "Pro" + } + ] + }, + "url": "/billing/plans", + "version": "6b16b94d7c51cbe5b1fa42aac98241d5", + "clearHistory": false, + "encryptHistory": false, + "onceProps": { + "plans": { + "prop": "plans", + "expiresAt": null + } + } +} +``` + +When navigating to a subsequent page that includes the same once prop, the client sends the loaded keys in the `X-Inertia-Except-Once-Props` header. The server skips resolving these props and excludes them from the response. The client reuses the previously loaded values. + +```http +REQUEST +GET: https://example.com/billing/upgrade +Accept: text/html, application/xhtml+xml +X-Requested-With: XMLHttpRequest +X-Inertia: true +X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5 +X-Inertia-Except-Once-Props: plans + +RESPONSE +HTTP/1.1 200 OK +Content-Type: application/json + +{ + "component": "Billing/Upgrade", + "props": { + "errors": {}, + "currentPlan": { + "id": 1, + "name": "Basic" + } + }, + "url": "/billing/upgrade", + "version": "6b16b94d7c51cbe5b1fa42aac98241d5", + "clearHistory": false, + "encryptHistory": false, + "onceProps": { + "plans": { + "prop": "plans", + "expiresAt": null + } + } +} +``` + +Note that `plans` is included in `onceProps` but not in `props` since it was already loaded on the client. The `onceProps` key identifies the once prop across pages, while `prop` specifies the actual prop name. These may differ when using [custom keys](/v2/data-props/once-props#custom-keys). + ## Asset Versioning One common challenge with single-page apps is refreshing site assets when they've been changed. Inertia makes this easy by optionally tracking the current version of the site's assets. In the event that an asset changes, Inertia will automatically make a full-page visit instead of an XHR visit. diff --git a/v2/data-props/deferred-props.mdx b/v2/data-props/deferred-props.mdx index 074e19c..4de1fe0 100644 --- a/v2/data-props/deferred-props.mdx +++ b/v2/data-props/deferred-props.mdx @@ -109,6 +109,8 @@ export default () => ( +## Multiple Deferred Props + If you need to wait for multiple deferred props to become available, you can specify an array to the `data` prop. @@ -173,3 +175,15 @@ export default () => ( ``` + +## Combining with Once Props + +You may chain the `once()` modifier onto a deferred prop to ensure the data is resolved only once and remembered by the client across subsequent navigations. + +```php +return Inertia::render('Dashboard', [ + 'stats' => Inertia::defer(fn () => Stats::generate())->once(), +]); +``` + +For more information on once props, see the [once props](/v2/data-props/once-props) documentation. diff --git a/v2/data-props/merging-props.mdx b/v2/data-props/merging-props.mdx index 3349372..04aca74 100644 --- a/v2/data-props/merging-props.mdx +++ b/v2/data-props/merging-props.mdx @@ -109,7 +109,7 @@ You can also merge props directly on the client side without making a server req ## Combining with Deferred Props -You can also combine [deferred props](/v2/data-props/deferred-props) with mergeable props to defer the loading of the prop and ultimately mark it as mergeable once it's loaded. +You may combine [deferred props](/v2/data-props/deferred-props) with mergeable props to defer the loading of the prop and ultimately mark it as mergeable once it's loaded. ```php Route::get('/users', function () { @@ -122,6 +122,18 @@ Route::get('/users', function () { }); ``` +## Combining with Once Props + +You may chain the `once()` modifier onto a merge prop to ensure the data is resolved only once and remembered by the client across subsequent navigations. + +```php +return Inertia::render('Users/Index', [ + 'activity' => Inertia::merge(fn () => $user->recentActivity())->once(), +]); +``` + +For more information on once props, see the [once props](/v2/data-props/once-props) documentation. + ## Resetting Props On the client side, you can indicate to the server that you would like to reset the prop. This is useful when you want to clear the prop value before merging new data, such as when the user enters a new search query on a paginated list. diff --git a/v2/data-props/once-props.mdx b/v2/data-props/once-props.mdx new file mode 100644 index 0000000..f415c48 --- /dev/null +++ b/v2/data-props/once-props.mdx @@ -0,0 +1,143 @@ +--- +title: Once Props +--- + +Some data rarely changes, is expensive to compute, or is simply large. Rather than including this data in every response, you may use _once props_. These props are remembered by the client and reused on subsequent pages that include the same prop. This makes them ideal for [shared data](/v2/data-props/shared-data). + +## Creating Once Props + +To create a once prop, use the `Inertia::once()` method when returning your response. This method receives a callback that returns the prop data. + +```php +return Inertia::render('Billing', [ + 'plans' => Inertia::once(fn () => Plan::all()), +]); +``` + +After the client has received this prop, subsequent requests will skip resolving the callback and exclude the prop from the response. The client only remembers once props while navigating between pages that include them. + +Navigating to a page without the once prop will forget the remembered value, and it will be resolved again on the next page that has it. In practice, this is rarely an issue since once props are typically used as shared data or within a specific section of your application. + +## Forcing a Refresh + +You may force a once prop to be refreshed using the `fresh()` method. + +```php +return Inertia::render('Billing', [ + 'plans' => Inertia::once(fn () => Plan::all())->fresh(), +]); +``` + +This method also accepts a boolean, allowing you to conditionally refresh the prop. + +```php +return Inertia::render('Billing', [ + 'plans' => Inertia::once(fn () => Plan::all())->fresh($condition), +]); +``` + +## Refreshing from the Client + +You may refresh a once prop from the client-side using a [partial reload](/v2/data-props/partial-reloads). The server will always resolve a once prop when explicitly requested. + + + +```js Vue icon="vuejs" +import { router } from '@inertiajs/vue3' + +router.reload({ only: ['plans'] }) +``` + +```js React icon="react" +import { router } from '@inertiajs/react' + +router.reload({ only: ['plans'] }) +``` + +```js Svelte icon="s" +import { router } from '@inertiajs/svelte' + +router.reload({ only: ['plans'] }) +``` + + + +## Expiration + +You may set an expiration time using the `until()` method. This method accepts a `DateTimeInterface`, `DateInterval`, or an integer (seconds). The prop will be refreshed on a subsequent visit after the expiration time has passed. + +```php +return Inertia::render('Dashboard', [ + 'rates' => Inertia::once(fn () => ExchangeRate::all())->until(now()->addDay()), +]); +``` + +## Custom Keys + +You may assign a custom key to the prop using the `as()` method. This is useful when you want to share data across multiple pages while using different prop names. + +```php +// Team member list... +return Inertia::render('Team/Index', [ + 'memberRoles' => Inertia::once(fn () => Role::all())->as('roles'), +]); + +// Invite form... +return Inertia::render('Team/Invite', [ + 'availableRoles' => Inertia::once(fn () => Role::all())->as('roles'), +]); +``` + +Both pages share the same underlying data because they use the same custom key, so the prop is only resolved for whichever page you visit first. + +## Sharing Once Props + +You may share once props globally using the `Inertia::share()` method. + +```php +Inertia::share('countries', Inertia::once(fn () => Country::all())); +``` + +Or, for convenience, you may use the `shareOnce()` method. + +```php +Inertia::shareOnce('countries', fn () => Country::all()); +``` + +You may also chain `as()`, `fresh()`, and `until()` onto the `shareOnce` method. + +```php +Inertia::shareOnce('countries', fn () => Country::all())->until(now()->addDay()); +``` + +Additionally, you may define a dedicated `shareOnce()` method in your middleware. The middleware will evaluate both `share()` and `shareOnce()`, merging the results. + +```php +class HandleInertiaRequests extends Middleware +{ + public function shareOnce(Request $request): array + { + return array_merge(parent::shareOnce($request), [ + 'countries' => fn () => Country::all(), + ]); + } +} +``` + +## Prefetching + +Once props are compatible with [prefetching](/v2/data-props/prefetching). The client automatically includes any remembered once props in prefetched responses, so navigating to a prefetched page will already have the once props available. + +Prefetched pages containing an expired once prop will be invalidated from the cache. + +## Combining with Other Prop Types + +The `once()` modifier may be chained onto [deferred](/v2/data-props/deferred-props), [merge](/v2/data-props/merging-props), and [optional](/v2/data-props/partial-reloads#lazy-data-evaluation) props. + +```php +return Inertia::render('Dashboard', [ + 'permissions' => Inertia::defer(fn () => Permission::all())->once(), + 'activity' => Inertia::merge(fn () => $user->recentActivity())->once(), + 'categories' => Inertia::optional(fn () => Category::all())->once(), +]); +``` diff --git a/v2/data-props/partial-reloads.mdx b/v2/data-props/partial-reloads.mdx index 18db183..b3a1720 100644 --- a/v2/data-props/partial-reloads.mdx +++ b/v2/data-props/partial-reloads.mdx @@ -163,3 +163,15 @@ Here's a summary of each approach: | `fn () => User::all()` | Always | Optionally | Only when needed | | | `Inertia::optional(fn () => User::all())` | Never | Optionally | Only when needed | | | `Inertia::always(fn () => User::all())` | Always | Always | Always | | + +## Combining with Once Props + +You may chain the `once()` modifier onto an optional prop to ensure the data is resolved only once and remembered by the client across subsequent navigations. + +```php +return Inertia::render('Users/Index', [ + 'users' => Inertia::optional(fn () => User::all())->once(), +]); +``` + +For more information on once props, see the [once props](/v2/data-props/once-props) documentation. diff --git a/v2/data-props/shared-data.mdx b/v2/data-props/shared-data.mdx index f8e0090..c8f9b41 100644 --- a/v2/data-props/shared-data.mdx +++ b/v2/data-props/shared-data.mdx @@ -47,6 +47,42 @@ Shared data should be used sparingly as all shared data is included with every r Page props and shared data are merged together, so be sure to namespace your shared data appropriately to avoid collisions. +## Sharing Once Props + +You may share data that is resolved only once and remembered by the client across subsequent navigations using [once props](/v2/data-props/once-props). + +```php +class HandleInertiaRequests extends Middleware +{ + public function share(Request $request) + { + return array_merge(parent::share($request), [ + 'countries' => Inertia::once(fn () => Country::all()), + ]); + } +} +``` + +Alternatively, you may define a dedicated `shareOnce()` method in the middleware. The middleware will evaluate both `share()` and `shareOnce()`, merging the results. + +```php +class HandleInertiaRequests extends Middleware +{ + public function shareOnce(Request $request): array + { + return array_merge(parent::shareOnce($request), [ + 'countries' => fn () => Country::all(), + ]); + } +} +``` + +You may also share once props manually using the `Inertia::shareOnce()`. + +```php +Inertia::shareOnce('countries', fn () => Country::all()); +``` + ## Accessing Shared Data Once you have shared the data server-side, you will be able to access it within any of your pages or components. Here's an example of how to access shared data in a layout component.