Skip to content

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.

gts
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 ​

ts
function usePoll(
  owner: object,
  interval: number,
  requestOptions?: ReloadOptions | (() => ReloadOptions),
  options?: PollOptions,
): Poll;

Arguments ​

NameTypeDefaultDescription
ownerobjectThe component (or any destroyable) that owns the poll. It stops when the owner is destroyed.
intervalnumberMilliseconds between reloads.
requestOptionsReloadOptions | (() => ReloadOptions){}The options of each reload, as router.reload() takes them: only, except, data, headers, callbacks… A function is called before every reload.
optionsPollOptions{}How the poll runs; see below.

PollOptions:

NameTypeDefaultDescription
autoStartbooleantrueStart 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.
keepAlivebooleanfalseDeprecated: use background: 'continue'.

Returns ​

Poll:

NameTypeDescription
pollingbooleanWhether it's running. Tracked.
start()() => voidStarts (or restarts) the poll.
stop()() => voidStops 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:

gts
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 ​

gts
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:

ts
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 ​

ts
function usePrefetch(owner: object, options?: VisitOptions): Prefetch;

Arguments ​

NameTypeDefaultDescription
ownerobjectThe component that owns it. Its event listeners are removed when the owner is destroyed.
optionsVisitOptions{}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:

NameTypeDescription
isPrefetchedbooleanWhether a prefetched response for this page is in the cache. Tracked.
isPrefetchingbooleanWhether a prefetch of this page is in flight. Tracked.
lastUpdatedAtnumber | nullWhen the cached response was fetched (a timestamp). Tracked: a new prefetch updates it.
flush()() => voidRemoves this page from the prefetch cache.

Examples ​

Show stale data and offer a refresh ​

gts
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 ​

ts
function useProp<T = unknown>(owner: object, name: string): Prop<T>;

Arguments ​

NameTypeDefaultDescription
ownerobjectThe component that owns it. It stops listening when it's destroyed.
namestringThe prop's name, or a dot path into it (order.total).

Returns ​

Prop<T>, all tracked:

NameTypeDescription
valueT | undefinedThe prop's current value, read from the page.
loadingbooleanWhether a request that refreshes this prop is in flight.
loadedbooleanWhether 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:

gts
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 ​

ts
function useRemember<T extends object>(initialState: T, key?: string): T;

Arguments ​

NameTypeDefaultDescription
initialStateTThe state to start with when there's nothing remembered. It's copied, not changed.
keystring'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 ​

gts
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:

ts
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.

Released under the MIT License.