Skip to content

useHttp ​

Form state for plain HTTP endpoints: the same fields, errors and states as useForm, but the request is an ordinary HTTP call instead of an Inertia visit, so the page stays put. Each request returns a promise of the response body.

gts
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useHttp } from 'inertia-ember';

export default class Newsletter extends Component {
  signup = useHttp({ email: '' });

  subscribe = async (event: SubmitEvent) => {
    event.preventDefault();
    await this.signup.post('/api/subscribers');
  };

  <template>
    <form {{on 'submit' this.subscribe}}>
      <input type='email' {{bind this.signup 'email'}} />
      {{#if this.signup.errors.email}}<p>{{this.signup.errors.email}}</p>{{/if}}
      <button disabled={{this.signup.processing}}>Subscribe</button>
      {{#if this.signup.wasSuccessful}}<p>Thanks!</p>{{/if}}
    </form>
  </template>
}

Signature ​

ts
function useHttp<TForm extends object = FormData, TResponse = unknown>(
  data?: TForm | (() => TForm),
): Http<TForm, TResponse>;

// Remembers the fields and errors in history under `rememberKey`.
function useHttp<TForm extends object = FormData, TResponse = unknown>(
  rememberKey: string | null | undefined,
  data: TForm | (() => TForm),
): Http<TForm, TResponse>;

// Turns on Precognition against this method and URL; `submit()` sends there.
function useHttp<TForm extends object = FormData, TResponse = unknown>(
  method: Method | (() => Method),
  url: string | (() => string),
  data: TForm | (() => TForm),
): Http<TForm, TResponse>;
function useHttp<TForm extends object = FormData, TResponse = unknown>(
  action: UrlMethodPair | (() => UrlMethodPair),
  data: TForm | (() => TForm),
): Http<TForm, TResponse>;

// The form and its fields. Exported as the type `UseHttp`.
type Http<TForm, TResponse> = InertiaHttp<TForm, TResponse> & TForm;

The arguments are the same as useForm's: see its table. TResponse types the response body: useHttp<{ q: string }, Result[]>({ q: '' }).

Properties ​

Everything useForm has (form.<field>, errors, hasErrors, isDirty, processing, progress, wasSuccessful, recentlySuccessful, validating), plus:

NameTypeDescription
responseTResponse | nullThe body of the last successful response, parsed as JSON. Tracked.

Methods ​

The field, error, defaults and Precognition methods are useForm's: data, set, transform, defaults, reset, setError, setErrors, clearErrors, forgetError, resetAndClearErrors, dontRemember, withPrecognition, validate, touch, touched, valid, invalid, validator, setValidationTimeout, validateFiles, withoutFileValidation and withAllErrors. See useForm. Sending differs:

NameTypeDescription
get, post, put, patch, delete, query(url: string, options?: HttpSubmitOptions) => Promise<TResponse | undefined>Send the fields. Resolves to the response body, or undefined after a 422.
submit(method, url, options?)
(action: UrlMethodPair, options?)
(options?), each returning the same promise
The same, with the method as an argument. Without a method and URL it sends to the Precognition endpoint, and throws if there isn't one.
cancel() => voidAbort the request in flight. Its promise rejects with HttpCancelledError.
optimistic(callback: (currentData: TForm) => Partial<TForm> | void) => thisChange the fields for the next request, and restore them if it fails.

The request ​

  • GET puts the fields in the query string. Other methods send JSON, or multipart/form-data when a field holds a file.
  • The request has Accept: application/json (and Content-Type: application/json for JSON), plus options.headers.
  • It goes through Inertia core's http client, re-exported by inertia-ember; http.setClient(…) swaps it.
  • The response body has to be JSON, or empty (which gives null).

What each outcome does ​

The server answersThe promiseThe form
2xxResolves to the bodyErrors cleared, response set, wasSuccessful true, the sent data becomes the defaults.
422 with { "errors": { … } }Resolves to undefinederrors filled: the first message per field, or every one with withAllErrors(). onError runs.
Any other statusRejects with HttpResponseErroronHttpException runs with the response.
Nothing (network failure)Rejects with the erroronNetworkError runs.
cancel() was calledRejects with HttpCancelledErroronCancel runs.

An optimistic change is rolled back on every outcome but 2xx. processing and progress reset and onFinish runs in every case. HttpResponseError and HttpCancelledError are exported by @inertiajs/core.

Options ​

HttpSubmitOptions is Inertia core's UseHttpSubmitOptions:

OptionTypeDescription
headersHttpRequestHeadersExtra request headers.
optimistic(currentData: TForm) => Partial<TForm> | voidAs optimistic(), for this request.
onBefore() => boolean | voidReturn false to stop: nothing is sent and the promise rejects.
onStart() => voidThe request is about to go out.
onProgress(progress: HttpProgressEvent) => voidUpload progress.
onSuccess(response: TResponse, httpResponse: HttpResponse) => voidA 2xx: the parsed body and the raw response.
onError(errors: Errors) => voidA 422: the errors as they were put in form.errors.
onHttpException(response: HttpResponse) => boolean | voidAny other non-2xx status.
onNetworkError(error: Error) => boolean | voidNo response.
onCancel() => voidThe request was cancelled.
onCancelToken(token: { cancel: () => void }) => voidA token that cancels this request.
onFinish() => voidAfter any outcome.

Examples ​

Search as the user types ​

response keeps the last result, so the template reads it directly. Cancel the previous request so an old answer can't land after a newer one; its promise rejects with HttpCancelledError.

gts
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { HttpCancelledError } from '@inertiajs/core';
import { useHttp } from 'inertia-ember';

interface Result {
  id: number;
  title: string;
}

export default class Search extends Component {
  search = useHttp<{ q: string }, Result[]>({ q: '' });

  lookUp = async (event: Event) => {
    this.search.q = (event.target as HTMLInputElement).value;
    this.search.cancel();

    try {
      await this.search.get('/api/search'); // GET /api/search?q=…
    } catch (error) {
      if (!(error instanceof HttpCancelledError)) throw error;
    }
  };

  <template>
    <input type='search' value={{this.search.q}} {{on 'input' this.lookUp}} />
    {{#if this.search.processing}}<span>Searching…</span>{{/if}}
    <ul>
      {{#each this.search.response as |result|}}
        <li>{{result.title}}</li>
      {{/each}}
    </ul>
  </template>
}

Post JSON and show validation errors ​

A 422 doesn't throw: the promise resolves to undefined and errors holds the messages, so check the result before using it.

ts
signup = useHttp<{ email: string }, { id: number }>({ email: '' });

subscribe = async (event: SubmitEvent) => {
  event.preventDefault();
  const subscriber = await this.signup.post('/api/subscribers');

  if (subscriber) {
    this.signup.reset();
    // subscriber.id …
  }
};

The server answers a 422 with a JSON body such as { "errors": { "email": ["Already subscribed."] } }.

Handle other failures ​

Statuses other than 2xx and 422 reject. Catch them, or use the callbacks.

ts
save = async () => {
  try {
    await this.settings.put('/api/settings', {
      onHttpException: (response) => {
        if (response.status === 403) this.message = 'You can’t change these settings.';
      },
    });
  } catch {
    // HttpResponseError, or a network error
  }
};

Update the fields before the server answers ​

optimistic returns the fields to change now. If the request fails, they're restored.

gts
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { useHttp } from 'inertia-ember';

export default class Star extends Component<{ Args: { repoId: number; starred: boolean } }> {
  star = useHttp({ starred: this.args.starred });

  toggle = async () => {
    await this.star
      .optimistic((data) => ({ starred: !data.starred }))
      .put(`/api/repos/${this.args.repoId}/star`)
      .catch(() => {}); // rolled back; show a message here if you like
  };

  <template>
    <button type='button' aria-pressed={{if this.star.starred 'true' 'false'}} {{on 'click' this.toggle}}>
      {{if this.star.starred 'Starred' 'Star'}}
    </button>
  </template>
}

The fields are sent after the change, so the server receives { "starred": true } when starring.

Upload a file with progress ​

gts
import Component from '@glimmer/component';
import { on } from '@ember/modifier';
import { bind, useHttp } from 'inertia-ember';

export default class Import extends Component {
  upload = useHttp<{ file: File | null }, { rows: number }>({ file: null });

  send = async (event: SubmitEvent) => {
    event.preventDefault();
    await this.upload.post('/api/imports');
  };

  <template>
    <form {{on 'submit' this.send}}>
      <input type='file' accept='.csv' {{bind this.upload 'file'}} />
      {{#if this.upload.progress}}
        <progress value={{this.upload.progress.percentage}} max='100'></progress>
      {{/if}}
      {{#if this.upload.response}}<p>Imported {{this.upload.response.rows}} rows.</p>{{/if}}
      <button disabled={{this.upload.processing}}>Import</button>
    </form>
  </template>
}

Validate with Precognition ​

With a method and URL first, validate and the rest work as in useForm, and submit() sends to the same endpoint.

ts
signup = useHttp('post', '/api/subscribers', { email: '' });

// <input {{bind this.signup 'email' validate=true}} />
subscribe = () => this.signup.submit();

Notes ​

  • Every method is bound to the form, so a template can pass this.form.submit or this.form.reset on its own. As handlers they ignore the event, and submit stops the browser's own submit.
  • Unlike useForm, optimistic changes the form's own fields, not the page's props.
  • onSuccess isn't awaited, and calling defaults() inside it keeps the automatic "sent data becomes the defaults" from running.

Related: useHttp guide, Precognition, useForm, {{bind}}.

Released under the MIT License.