Hooks
Ember doesn't have React-style hooks. usePoll, usePrefetch and useProp take the object that owns them (usually the component, this) and clean up when it's destroyed. useRemember needs no owner. Call them in a class field or the constructor.
import Component from '@glimmer/component';
import { usePoll } from 'inertia-ember';
export default class Dashboard extends Component {
poll = usePoll(this, 5000, { only: ['stats'] });
}usePoll
Reloads the current page every interval milliseconds while its owner lives, the same as router.poll().
Signature
function usePoll(
owner: object,
interval: number,
requestOptions?: ReloadOptions | (() => ReloadOptions),
options?: PollOptions,
): Poll;Arguments
| Name | Type | Default | Description |
|---|---|---|---|
owner | object | The component (or any destroyable) that owns the poll. It stops when the owner is destroyed. | |
interval | number | Milliseconds between reloads. | |
requestOptions | ReloadOptions | (() => ReloadOptions) | {} | The options of each reload, as router.reload() takes them: only, except, data, headers, callbacks… A function is called before every reload. |
options | PollOptions | {} | How the poll runs; see below. |
PollOptions:
| Name | Type | Default | Description |
|---|---|---|---|
autoStart | boolean | true | Start right away. With false, call start() yourself. |
background | 'throttle' | 'pause' | 'continue' | 'throttle' | What happens while the tab is hidden: throttle reloads on one tick in ten, pause stops until the tab is visible again, continue keeps going. |
mode | 'overlap' | 'cancel' | 'rest' | 'overlap' | When a reload is still running at the next tick: overlap sends another, cancel cancels the running one first, rest waits interval after each reload finishes. |
keepAlive | boolean | false | Deprecated: use background: 'continue'. |
Returns
Poll:
| Name | Type | Description |
|---|---|---|
polling | boolean | Whether it's running. Tracked. |
start() | () => void | Starts (or restarts) the poll. |
stop() | () => void | Stops it until the next start(). |
While rendering on the server it does nothing and polling is false.
Examples
Refresh one prop
The server sends a stats prop; reload only that one, every five seconds:
import Component from '@glimmer/component';
import { type PageSignature, usePoll } from 'inertia-ember';
interface Props {
stats: { visitors: number; orders: number };
}
export default class Dashboard extends Component<PageSignature<Props>> {
poll = usePoll(this, 5000, { only: ['stats'] });
<template>
<p>{{@props.stats.visitors}} visitors, {{@props.stats.orders}} orders</p>
</template>
}Pause and resume
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { usePoll } from 'inertia-ember';
export default class Feed extends Component {
poll = usePoll(this, 2000, { only: ['entries'] }, { autoStart: false });
toggle = () => (this.poll.polling ? this.poll.stop() : this.poll.start());
<template>
<button type='button' {{on 'click' this.toggle}}>
{{if this.poll.polling 'Pause' 'Follow live'}}
</button>
</template>
}Send the latest state with each reload
A function as requestOptions is read before every reload, so it can send what the page holds now:
poll = usePoll(this, 10_000, () => ({ only: ['messages'], data: { since: this.lastSeenId } }), { mode: 'rest' });usePrefetch
Whether the current page came from the prefetch cache, and a way to drop it from the cache.
Signature
function usePrefetch(owner: object, options?: VisitOptions): Prefetch;Arguments
| Name | Type | Default | Description |
|---|---|---|---|
owner | object | The component that owns it. Its event listeners are removed when the owner is destroyed. | |
options | VisitOptions | {} | The visit options the page was prefetched with (data, method…), which are part of the cache key. |
Returns
Prefetch, for the current URL's path:
| Name | Type | Description |
|---|---|---|
isPrefetched | boolean | Whether a prefetched response for this page is in the cache. Tracked. |
isPrefetching | boolean | Whether a prefetch of this page is in flight. Tracked. |
lastUpdatedAt | number | null | When the cached response was fetched (a timestamp). Tracked: a new prefetch updates it. |
flush() | () => void | Removes this page from the prefetch cache. |
Examples
Show stale data and offer a refresh
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { router, usePrefetch } from 'inertia-ember';
export default class Inbox extends Component {
prefetch = usePrefetch(this);
refresh = () => {
this.prefetch.flush();
router.reload();
};
<template>
{{#if this.prefetch.isPrefetched}}
<p>Showing a cached copy. <button type='button' {{on 'click' this.refresh}}>Refresh</button></p>
{{/if}}
</template>
}useProp
One prop of the current page, with its loading state: whether a partial reload, a deferred load or a live update that covers it is in flight. Useful to show a spinner next to the one value that's refreshing.
Signature
function useProp<T = unknown>(owner: object, name: string): Prop<T>;Arguments
| Name | Type | Default | Description |
|---|---|---|---|
owner | object | The component that owns it. It stops listening when it's destroyed. | |
name | string | The prop's name, or a dot path into it (order.total). |
Returns
Prop<T>, all tracked:
| Name | Type | Description |
|---|---|---|
value | T | undefined | The prop's current value, read from the page. |
loading | boolean | Whether a request that refreshes this prop is in flight. |
loaded | boolean | Whether the prop has a value (false while a deferred prop hasn't arrived). |
Examples
A spinner next to a refreshing value
The server sends an order prop and refreshes it with partial reloads or live updates:
import Component from '@glimmer/component';
import { useProp } from 'inertia-ember';
interface Order {
status: string;
total: number;
}
export default class OrderStatus extends Component {
order = useProp<Order>(this, 'order');
<template>
{{#if this.order.loaded}}
<p>{{this.order.value.status}} {{if this.order.loading '(updating…)'}}</p>
{{else}}
<p>Loading…</p>
{{/if}}
</template>
}useRemember
Local state that survives back and forward navigation. It returns a tracked object; every change is saved in the browser history entry, and coming back to that entry restores it.
Signature
function useRemember<T extends object>(initialState: T, key?: string): T;Arguments
| Name | Type | Default | Description |
|---|---|---|---|
initialState | T | The state to start with when there's nothing remembered. It's copied, not changed. | |
key | string | 'default' | Where it's saved in the history entry. Give each piece of state on a page its own key. |
Returns
A copy of T, tracked all the way down: nested objects and arrays included. Any change, at any depth (state.filters.tags.push('x')), re-renders what reads it and is saved to history. On the server it's a tracked copy that saves nothing.
Examples
Remember a view toggle
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { fn } from '@ember/helper';
import { useRemember } from 'inertia-ember';
export default class Products extends Component {
view = useRemember<{ mode: 'grid' | 'list' }>({ mode: 'grid' }, 'Products/view');
setMode = (mode: 'grid' | 'list') => (this.view.mode = mode);
<template>
<button type='button' {{on 'click' (fn this.setMode 'grid')}}>Grid</button>
<button type='button' {{on 'click' (fn this.setMode 'list')}}>List</button>
<div class={{this.view.mode}}>…</div>
</template>
}Update a list
Assign a new array, so the change is saved:
filters = useRemember({ tags: [] as string[] }, 'Products/filters');
addTag = (tag: string) => (this.filters.tags = [...this.filters.tags, tag]);To remember a form's fields and errors, pass a key to useForm instead.
Related: Hooks, Props that arrive later, Live props, router, usePage.