Router and core re-exports
router, progress, http and socketId are @inertiajs/core's own objects, re-exported so you import everything from inertia-ember. They work as in every other adapter; this page covers the calls you'll use most, with Ember examples. The full reference is at inertiajs.com.
import { on } from '@ember/modifier';
import { router } from 'inertia-ember';
const refresh = () => router.reload({ only: ['notifications'] });
<template>
<button type='button' {{on 'click' refresh}}>Check for new notifications</button>
</template>router
Makes Inertia visits from code: what <Link> and forms do, without an element. createInertiaApp starts it; while rendering on the server it isn't started.
Signature
router.visit(href: string | URL | UrlMethodPair, options?: VisitOptions): void;
router.get(url, data?, options?): void;
router.post(url, data?, options?): void;
router.put(url, data?, options?): void;
router.patch(url, data?, options?): void;
router.query(url, data?, options?): void; // the HTTP QUERY method
router.delete(url, options?): void;
router.reload(options?: ReloadOptions): void;
router.on(event: string, callback: (event: CustomEvent) => unknown): () => void;
router.once(event: string, callback: (event: CustomEvent) => unknown): () => void;
router.prefetch(href, options?: VisitOptions, prefetchOptions?: { cacheFor?; cacheTags? }): void;
router.flush(href, options?): void;
router.flushAll(): void;
router.flushByCacheTags(tags: string | string[]): void;
router.replace(params: ClientSideVisitOptions): void;
router.push(params: ClientSideVisitOptions): void;
router.replaceProp(name: string, value: unknown | ((old, props) => unknown)): void;
router.appendToProp(name: string, value: unknown | ((old, props) => unknown)): void;
router.prependToProp(name: string, value: unknown | ((old, props) => unknown)): void;
router.flash(keyOrData: string | object | ((flash) => object), value?: unknown): void;
router.optimistic(callback: (props) => Partial<props> | void): typeof router;
router.cancelAll(options?: { async?: boolean; prefetch?: boolean; sync?: boolean }): void;
router.poll(interval: number, requestOptions?, options?): { start(): void; stop(): void; destroy(): void };
router.remember(data: unknown, key?: string): void;
router.restore(key?: string): unknown;
router.clearHistory(): void;get, post, put, patch and query take (url, data, options), with options the visit options minus method and data. delete takes (url, options). Each starts a visit and returns nothing; react to it with the callbacks.
Visit options
The common ones; every <Link> argument maps to one of these.
| Name | Type | Default | Description |
|---|---|---|---|
method | 'get' | 'post' | 'put' | 'patch' | 'delete' | 'query' | 'get' | The HTTP method (visit only). |
data | Record<string, FormDataConvertible> | FormData | {} | The data: a query string for GET, the body otherwise. |
replace | boolean | false | Replace the history entry instead of adding one. |
preserveState | boolean | 'errors' | ((page) => boolean) | false | Keep the page component's state (same component, no remount). 'errors' keeps it only on errors. |
preserveScroll | boolean | 'errors' | ((page) => boolean) | false | Keep the scroll position. |
only | string[] | [] | Ask for these props only (a partial reload). |
except | string[] | [] | Ask for every prop but these. |
reset | string[] | [] | Props the server merges that should be replaced instead. |
headers | Record<string, string> | {} | Extra request headers. |
errorBag | string | null | none | Scope the validation errors to this bag. |
forceFormData | boolean | false | Send FormData even without files. |
async | boolean | false | Run alongside other visits instead of cancelling them, or being cancelled. |
showProgress | boolean | true | Show the progress bar. |
preserveUrl | boolean | false | Keep the current URL. |
viewTransition | boolean | ((transition: ViewTransition) => void) | false | Swap the page inside a View Transition. |
optimistic | (props) => Partial<props> | void | Change props right away, rolled back if the request fails. | |
onBefore, onStart, onProgress, onSuccess, onError, onFinish, onCancel, onCancelToken, onHttpException, onNetworkError, onFlash | functions | Callbacks for this visit only, named after the events. onBefore returning false cancels it. |
Events
router.on(name, callback) listens to every visit and returns a function that removes the listener. Each callback gets a CustomEvent whose detail holds the data. In a component, hand the remover to registerDestructor.
| Event | detail | Notes |
|---|---|---|
before | { visit } | Return false (or preventDefault()) to cancel the visit. |
start | { visit } | The request was sent. |
progress | { progress } | Upload progress, for requests sent as FormData. |
success | { page, visitId? } | The visit succeeded without validation errors. |
error | { errors, page?, visitId? } | The server answered with validation errors. |
finish | { visit } | After success, error or cancel. |
cancel | {} | The visit was cancelled. |
navigate | { page, type: 'initial' | 'visit' | 'history' } | A page was shown, including the first one and back/forward. |
beforeUpdate | { page } | Right before the page is swapped. |
httpException | { response } | A non-Inertia response. Return false to handle it yourself. |
networkError | { error } | The request failed. Return false to handle it yourself. |
flash | { flash } | Flash data arrived. |
prefetching, prefetched | { visit }, { response, fetchedAt, visit } | A prefetch started or finished. |
Also clientVisit, location and live; see inertiajs.com.
Examples
Visit from code
import { router } from 'inertia-ember';
router.visit('/orders?page=2');
router.post('/orders', { product_id: 7, quantity: 2 }, { preserveScroll: true });
router.delete(`/orders/${id}`, { onBefore: () => confirm('Delete this order?') });Reload some props
The server sends notifications and stats; ask for one again without leaving the page:
router.reload({ only: ['notifications'] });Filter a list as the user types
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { type PageSignature, router } from 'inertia-ember';
interface Props {
filters: { q: string };
products: { id: number; name: string }[];
}
export default class Products extends Component<PageSignature<Props>> {
search = (event: Event) => {
const q = (event.target as HTMLInputElement).value;
router.get('/products', { q }, { only: ['products', 'filters'], preserveState: true, replace: true });
};
<template>
<input type='search' value={{@props.filters.q}} {{on 'input' this.search}} />
<ul>
{{#each @props.products key='id' as |product|}}<li>{{product.name}}</li>{{/each}}
</ul>
</template>
}Listen to navigation
import Component from '@glimmer/component';
import type Owner from '@ember/owner';
import { registerDestructor } from '@ember/destroyable';
import { router } from 'inertia-ember';
export default class Analytics extends Component {
constructor(owner: Owner, args: object) {
super(owner, args);
const stop = router.on('navigate', (event) => {
trackPageView(event.detail.page.url); // your analytics call
});
registerDestructor(this, stop);
}
}A listener for the whole app can go in app.ts, next to createInertiaApp:
router.on('before', (event) => {
if (event.detail.visit.method !== 'get' && !navigator.onLine) {
return false; // cancels the visit
}
});Prefetch a page
router.prefetch('/reports', { method: 'get' }, { cacheFor: '1m', cacheTags: ['reports'] });
// Later, after something changes the reports:
router.flushByCacheTags('reports');<Link @prefetch> does the same on hover, click or mount.
Change props without a request
router.replaceProp('cart.count', (count: number) => count + 1);
router.appendToProp('messages', { id: 42, body: 'Hi' });
router.replace({ props: (props) => ({ ...props, filtersOpen: true }), preserveState: true });
router.flash('toast', 'Saved');Update props before the server answers
router.optimistic((props) => ({ likes: (props.likes as number) + 1 })).post(`/posts/${id}/like`);If the request fails, the props roll back.
progress
The progress bar Inertia shows during visits, configured by createInertiaApp's progress option. Drive it yourself for work that isn't a visit, such as a useHttp request.
| Method | Description |
|---|---|
start() | Shows the bar and starts it moving. |
set(status) | Sets it to status, between 0 and 1. |
finish() | Completes it and hides it. |
reset() | Sets it back to 0. |
remove() | Completes it and removes it from the page. |
hide(), reveal(force?) | Hide it while something else shows progress; reveal shows it again once every hide has been undone (or with force). |
isStarted() | Whether it's showing. |
getStatus() | Its position, or null. |
import { progress } from 'inertia-ember';
progress.start();
await uploadInChunks(file, (done) => progress.set(done));
progress.finish();http
The HTTP client behind every Inertia request (router, useForm, useHttp). Use it to add headers, read responses or report errors in one place, or to swap the client.
| Method | Description |
|---|---|
onRequest(handler) | Runs before each request with its config (method, url, data, headers…); return the config. Returns a remover. |
onResponse(handler) | Runs after each successful response (status, data, headers); return the response. Returns a remover. |
onError(handler) | Runs when a request fails (HttpResponseError, HttpNetworkError, HttpCancelledError). Returns a remover. |
setClient(clientOrOptions) | Replaces the client (an object with request(config): Promise<response>), or configures the default one (xsrfCookieName, xsrfHeaderName). createInertiaApp's http option calls it. |
getClient() | The current client. |
import { http } from 'inertia-ember';
http.onRequest((config) => ({
...config,
headers: { ...config.headers, 'X-Timezone': Intl.DateTimeFormat().resolvedOptions().timeZone },
}));
http.onError((error) => console.error('Request failed', error));socketId
Tells Inertia the id of this tab's websocket connection. Inertia sends it with every request as X-Socket-Id, so the server can leave this tab out when it broadcasts (Laravel's toOthers() and its equivalents).
| Method | Description |
|---|---|
resolveUsing(callback | null) | callback returns the id (or null/undefined when not connected). null stops sending it. |
resolveUsingDefault(callback) | Sets a resolver only if the app hasn't chosen one. For libraries. |
resolve() | The current id, or null. |
import { socketId } from 'inertia-ember';
socketId.resolveUsing(() => mySocket.id ?? null);Related: Links, Live props, Hooks, Setup, page, Link, inertiajs.com.