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.
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
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:
| Name | Type | Description |
|---|---|---|
response | TResponse | null | The 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:
| Name | Type | Description |
|---|---|---|
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 | () => void | Abort the request in flight. Its promise rejects with HttpCancelledError. |
optimistic | (callback: (currentData: TForm) => Partial<TForm> | void) => this | Change 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-datawhen a field holds a file. - The request has
Accept: application/json(andContent-Type: application/jsonfor JSON), plusoptions.headers. - It goes through Inertia core's
httpclient, 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 answers | The promise | The form |
|---|---|---|
| 2xx | Resolves to the body | Errors cleared, response set, wasSuccessful true, the sent data becomes the defaults. |
422 with { "errors": { … } } | Resolves to undefined | errors filled: the first message per field, or every one with withAllErrors(). onError runs. |
| Any other status | Rejects with HttpResponseError | onHttpException runs with the response. |
| Nothing (network failure) | Rejects with the error | onNetworkError runs. |
cancel() was called | Rejects with HttpCancelledError | onCancel 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:
| Option | Type | Description |
|---|---|---|
headers | HttpRequestHeaders | Extra request headers. |
optimistic | (currentData: TForm) => Partial<TForm> | void | As optimistic(), for this request. |
onBefore | () => boolean | void | Return false to stop: nothing is sent and the promise rejects. |
onStart | () => void | The request is about to go out. |
onProgress | (progress: HttpProgressEvent) => void | Upload progress. |
onSuccess | (response: TResponse, httpResponse: HttpResponse) => void | A 2xx: the parsed body and the raw response. |
onError | (errors: Errors) => void | A 422: the errors as they were put in form.errors. |
onHttpException | (response: HttpResponse) => boolean | void | Any other non-2xx status. |
onNetworkError | (error: Error) => boolean | void | No response. |
onCancel | () => void | The request was cancelled. |
onCancelToken | (token: { cancel: () => void }) => void | A token that cancels this request. |
onFinish | () => void | After 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.
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.
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.
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.
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
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.
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.submitorthis.form.reseton its own. As handlers they ignore the event, andsubmitstops the browser's own submit. - Unlike
useForm,optimisticchanges the form's own fields, not the page's props. onSuccessisn't awaited, and callingdefaults()inside it keeps the automatic "sent data becomes the defaults" from running.
Related: useHttp guide, Precognition, useForm, {{bind}}.