HTTP Requests
- Basic Usage
- Submitting Data
- Multiple Requests
- Reactive State
- Validation Errors
- Displaying All Errors
- File Uploads
- Canceling Requests
- Optimistic Updates
- Event Callbacks
- Precognition
- History State
Not every request needs to trigger an Inertia page visit. For calls to an external API or fetching data from a non-Inertia endpoint, the useHttp hook provides the same developer experience as useForm, but for standalone HTTP requests.
Basic Usage
The useHttp hook accepts initial data and returns reactive state along with methods for making HTTP requests.
1<script setup>2import { useHttp } from '@inertiajs/vue3'34const http = useHttp({5 query: '',6})78function search() {9 http.get('/api/search', {10 onSuccess: (response) => {11 console.log(response)12 },13 })14}15</script>1617<template>18 <input v-model="http.query" @input="search" />19 <div v-if="http.processing">Searching...</div>20</template>1<script setup>2import { useHttp } from '@inertiajs/vue3'34const http = useHttp({5 query: '',6})78function search() {9 http.get('/api/search', {10 onSuccess: (response) => {11 console.log(response)12 },13 })14}15</script>1617<template>18 <input v-model="http.query" @input="search" />19 <div v-if="http.processing">Searching...</div>20</template>
1import { useHttp } from '@inertiajs/react'23export default function Search() {4 const { data, setData, get, processing } = useHttp({5 query: '',6 })78 function search(e) {9 setData('query', e.target.value)10 get('/api/search', {11 onSuccess: (response) => {12 console.log(response)13 },14 })15 }1617 return (18 <>19 <input value={data.query} onChange={search} />20 {processing && <div>Searching...</div>}21 </>22 )23}1import { useHttp } from '@inertiajs/react'23export default function Search() {4 const { data, setData, get, processing } = useHttp({5 query: '',6 })78 function search(e) {9 setData('query', e.target.value)10 get('/api/search', {11 onSuccess: (response) => {12 console.log(response)13 },14 })15 }1617 return (18 <>19 <input value={data.query} onChange={search} />20 {processing && <div>Searching...</div>}21 </>22 )23}
1<script>2import { useHttp } from '@inertiajs/svelte'34const http = useHttp({5 query: '',6})78function search() {9 http.get('/api/search', {10 onSuccess: (response) => {11 console.log(response)12 },13 })14}15</script>1617<input bind:value={http.query} oninput={search} />18{#if http.processing}19 <div>Searching...</div>20{/if}1<script>2import { useHttp } from '@inertiajs/svelte'34const http = useHttp({5 query: '',6})78function search() {9 http.get('/api/search', {10 onSuccess: (response) => {11 console.log(response)12 },13 })14}15</script>1617<input bind:value={http.query} oninput={search} />18{#if http.processing}19 <div>Searching...</div>20{/if}
Unlike router visits, useHttp requests do not trigger page navigation or interact with Inertia's page lifecycle. They are plain HTTP requests that return JSON responses.
Submitting Data
The hook provides get, post, put, patch, delete, and query convenience methods. A generic submit method is also available for dynamic HTTP methods.
1http.get(url, options)2http.post(url, options)3http.put(url, options)4http.patch(url, options)5http.delete(url, options)6http.query(url, options)7http.submit(method, url, options)1http.get(url, options)2http.post(url, options)3http.put(url, options)4http.patch(url, options)5http.delete(url, options)6http.query(url, options)7http.submit(method, url, options)
1const { get, post, put, patch, delete: destroy, query, submit } = useHttp({ ... })23get(url, options)4post(url, options)5put(url, options)6patch(url, options)7destroy(url, options)8query(url, options)9submit(method, url, options)1const { get, post, put, patch, delete: destroy, query, submit } = useHttp({ ... })23get(url, options)4post(url, options)5put(url, options)6patch(url, options)7destroy(url, options)8query(url, options)9submit(method, url, options)
1http.get(url, options)2http.post(url, options)3http.put(url, options)4http.patch(url, options)5http.delete(url, options)6http.query(url, options)7http.submit(method, url, options)1http.get(url, options)2http.post(url, options)3http.put(url, options)4http.patch(url, options)5http.delete(url, options)6http.query(url, options)7http.submit(method, url, options)
Each method returns a Promise that resolves with the parsed JSON response data. TypeScript users may type the request data and response.
Pre-binding the Endpoint
You may pass the HTTP method and URL as the first two arguments to useHttp(), then call submit() without arguments to dispatch the request. This also unlocks real-time validation. See Precognition for details.
1const response = await http.post('/api/comments', {2 onError: (errors) => {3 console.log(errors)4 },5})1const response = await http.post('/api/comments', {2 onError: (errors) => {3 console.log(errors)4 },5})
1const response = await post('/api/comments', {2 onError: (errors) => {3 console.log(errors)4 },5})1const response = await post('/api/comments', {2 onError: (errors) => {3 console.log(errors)4 },5})
1const response = await http.post('/api/comments', {2 onError: (errors) => {3 console.log(errors)4 },5})1const response = await http.post('/api/comments', {2 onError: (errors) => {3 console.log(errors)4 },5})
Multiple Requests
Each useHttp instance tracks its own processing, errors, and other reactive state. When making independent requests, you may create a separate instance for each one so their states don't collide.
1const search = useHttp({ query: '' })2const upload = useHttp({ file: null })1const search = useHttp({ query: '' })2const upload = useHttp({ file: null })
1const search = useHttp({ query: '' })2const upload = useHttp({ file: null })1const search = useHttp({ query: '' })2const upload = useHttp({ file: null })
1const search = useHttp({ query: '' })2const upload = useHttp({ file: null })1const search = useHttp({ query: '' })2const upload = useHttp({ file: null })
Reactive State
The useHttp hook exposes the same reactive properties as useForm:
| Property | Type | Description |
|---|---|---|
errors |
object |
Validation errors keyed by field name |
hasErrors |
boolean |
Whether validation errors exist |
processing |
boolean |
Whether a request is in progress |
progress |
object | null |
Upload progress with percentage and total |
wasSuccessful |
boolean |
Whether the last request was successful |
recentlySuccessful |
boolean |
true for two seconds after a successful request |
isDirty |
boolean |
Whether the data differs from its defaults |
Validation Errors
When a request returns a 422 status code, the hook automatically parses validation errors and makes them available through the errors property.
1<script setup>2import { useHttp } from '@inertiajs/vue3'34const http = useHttp({5 name: '',6 email: '',7})89function save() {10 http.post('/api/users')11}12</script>1314<template>15 <input v-model="http.name" />16 <div v-if="http.errors.name">{{ http.errors.name }}</div>1718 <input v-model="http.email" />19 <div v-if="http.errors.email">{{ http.errors.email }}</div>2021 <button @click="save" :disabled="http.processing">Save</button>22</template>1<script setup>2import { useHttp } from '@inertiajs/vue3'34const http = useHttp({5 name: '',6 email: '',7})89function save() {10 http.post('/api/users')11}12</script>1314<template>15 <input v-model="http.name" />16 <div v-if="http.errors.name">{{ http.errors.name }}</div>1718 <input v-model="http.email" />19 <div v-if="http.errors.email">{{ http.errors.email }}</div>2021 <button @click="save" :disabled="http.processing">Save</button>22</template>
1import { useHttp } from '@inertiajs/react'23export default function CreateUser() {4 const { data, setData, post, errors, processing } = useHttp({5 name: '',6 email: '',7 })89 function save(e) {10 e.preventDefault()11 post('/api/users')12 }1314 return (15 <form onSubmit={save}>16 <input value={data.name} onChange={e => setData('name', e.target.value)} />17 {errors.name && <div>{errors.name}</div>}1819 <input value={data.email} onChange={e => setData('email', e.target.value)} />20 {errors.email && <div>{errors.email}</div>}2122 <button type="submit" disabled={processing}>Save</button>23 </form>24 )25}1import { useHttp } from '@inertiajs/react'23export default function CreateUser() {4 const { data, setData, post, errors, processing } = useHttp({5 name: '',6 email: '',7 })89 function save(e) {10 e.preventDefault()11 post('/api/users')12 }1314 return (15 <form onSubmit={save}>16 <input value={data.name} onChange={e => setData('name', e.target.value)} />17 {errors.name && <div>{errors.name}</div>}1819 <input value={data.email} onChange={e => setData('email', e.target.value)} />20 {errors.email && <div>{errors.email}</div>}2122 <button type="submit" disabled={processing}>Save</button>23 </form>24 )25}
1<script>2import { useHttp } from '@inertiajs/svelte'34const http = useHttp({5 name: '',6 email: '',7})89function save() {10 http.post('/api/users')11}12</script>1314<input bind:value={http.name} />15{#if http.errors.name}16 <div>{http.errors.name}</div>17{/if}1819<input bind:value={http.email} />20{#if http.errors.email}21 <div>{http.errors.email}</div>22{/if}2324<button onclick={save} disabled={http.processing}>Save</button>1<script>2import { useHttp } from '@inertiajs/svelte'34const http = useHttp({5 name: '',6 email: '',7})89function save() {10 http.post('/api/users')11}12</script>1314<input bind:value={http.name} />15{#if http.errors.name}16 <div>{http.errors.name}</div>17{/if}1819<input bind:value={http.email} />20{#if http.errors.email}21 <div>{http.errors.email}</div>22{/if}2324<button onclick={save} disabled={http.processing}>Save</button>
Displaying All Errors
By default, validation errors are simplified to the first error message for each field. You may chain withAllErrors() to receive all error messages as arrays, which is useful for fields with multiple validation rules.
1const http = useHttp({2 name: '',3 email: '',4}).withAllErrors()56// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']1const http = useHttp({2 name: '',3 email: '',4}).withAllErrors()56// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']
1const http = useHttp({2 name: '',3 email: '',4}).withAllErrors()56// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']1const http = useHttp({2 name: '',3 email: '',4}).withAllErrors()56// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']
1const http = useHttp({2 name: '',3 email: '',4}).withAllErrors()56// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']1const http = useHttp({2 name: '',3 email: '',4}).withAllErrors()56// http.errors.name === ['Name is required.', 'Name must be at least 3 characters.']
The same method is available on the useForm helper and the <Form> component.
File Uploads
When the data includes files, the hook automatically sends the request as multipart/form-data. Upload progress is available through the progress property.
1<script setup>2import { useHttp } from '@inertiajs/vue3'34const http = useHttp({5 file: null,6})78function upload() {9 http.post('/api/uploads')10}11</script>1213<template>14 <input type="file" @change="http.file = $event.target.files[0]" />15 <progress v-if="http.progress" :value="http.progress.percentage" max="100" />16 <button @click="upload" :disabled="http.processing">Upload</button>17</template>1<script setup>2import { useHttp } from '@inertiajs/vue3'34const http = useHttp({5 file: null,6})78function upload() {9 http.post('/api/uploads')10}11</script>1213<template>14 <input type="file" @change="http.file = $event.target.files[0]" />15 <progress v-if="http.progress" :value="http.progress.percentage" max="100" />16 <button @click="upload" :disabled="http.processing">Upload</button>17</template>
1import { useHttp } from '@inertiajs/react'23export default function Upload() {4 const { setData, post, progress, processing } = useHttp({5 file: null,6 })78 return (9 <>10 <input type="file" onChange={e => setData('file', e.target.files[0])} />11 {progress && <progress value={progress.percentage} max="100" />}12 <button onClick={() => post('/api/uploads')} disabled={processing}>Upload</button>13 </>14 )15}1import { useHttp } from '@inertiajs/react'23export default function Upload() {4 const { setData, post, progress, processing } = useHttp({5 file: null,6 })78 return (9 <>10 <input type="file" onChange={e => setData('file', e.target.files[0])} />11 {progress && <progress value={progress.percentage} max="100" />}12 <button onClick={() => post('/api/uploads')} disabled={processing}>Upload</button>13 </>14 )15}
1<script>2import { useHttp } from '@inertiajs/svelte'34const http = useHttp({5 file: null,6})78function upload() {9 http.post('/api/uploads')10}11</script>1213<input type="file" onchange={e => http.file = e.target.files[0]} />14{#if http.progress}15 <progress value={http.progress.percentage} max="100" />16{/if}17<button onclick={upload} disabled={http.processing}>Upload</button>1<script>2import { useHttp } from '@inertiajs/svelte'34const http = useHttp({5 file: null,6})78function upload() {9 http.post('/api/uploads')10}11</script>1213<input type="file" onchange={e => http.file = e.target.files[0]} />14{#if http.progress}15 <progress value={http.progress.percentage} max="100" />16{/if}17<button onclick={upload} disabled={http.processing}>Upload</button>
Canceling Requests
You may cancel an in-progress request using the cancel() method.
1http.cancel()1http.cancel()
1const { cancel } = useHttp({ ... })23cancel()1const { cancel } = useHttp({ ... })23cancel()
1http.cancel()1http.cancel()
Optimistic Updates
The useHttp hook supports optimistic updates via the optimistic() method. The callback receives the current data and should return a partial update to apply immediately.
1http.optimistic((data) => ({2 likes: data.likes + 1,3})).post('/api/likes')1http.optimistic((data) => ({2 likes: data.likes + 1,3})).post('/api/likes')
1const { optimistic, post } = useHttp({ likes: 0 })23optimistic((data) => ({4 likes: data.likes + 1,5}))6post('/api/likes')1const { optimistic, post } = useHttp({ likes: 0 })23optimistic((data) => ({4 likes: data.likes + 1,5}))6post('/api/likes')
1http.optimistic((data) => ({2 likes: data.likes + 1,3})).post('/api/likes')1http.optimistic((data) => ({2 likes: data.likes + 1,3})).post('/api/likes')
The update is applied synchronously. If the request fails, the data is rolled back to its previous state.
Event Callbacks
Each submit method accepts an options object with lifecycle callbacks:
1http.post('/api/users', {2 onBefore: () => { ... },3 onStart: () => { ... },4 onProgress: (progress) => { ... },5 onSuccess: (data, response) => { ... },6 onError: (errors) => { ... },7 onHttpException: (response) => { ... },8 onNetworkError: (error) => { ... },9 onCancel: () => { ... },10 onFinish: () => { ... },11})1http.post('/api/users', {2 onBefore: () => { ... },3 onStart: () => { ... },4 onProgress: (progress) => { ... },5 onSuccess: (data, response) => { ... },6 onError: (errors) => { ... },7 onHttpException: (response) => { ... },8 onNetworkError: (error) => { ... },9 onCancel: () => { ... },10 onFinish: () => { ... },11})
You may return false from onBefore to cancel the request.
Accessing the HTTP response
The onSuccess callback receives the parsed response data as its first argument and the HTTP response object as its second argument. The response object contains status, data, and headers properties, which is useful when you need to inspect the status code or response headers.
1http.post('/api/users', {2 onSuccess: (data, response) => {3 console.log(response.status) // 200, 201, etc.4 },5})1http.post('/api/users', {2 onSuccess: (data, response) => {3 console.log(response.status) // 200, 201, etc.4 },5})
HTTP exceptions
The onHttpException callback fires when the server returns a non-422 HTTP error, such as a 500 or 403. The callback receives the HTTP response object, giving you access to the status code, response body, and headers.
1http.post('/api/users', {2 onHttpException: (response) => {3 console.log(response.status) // 500, 403, etc.4 console.log(response.data) // Response body5 },6})1http.post('/api/users', {2 onHttpException: (response) => {3 console.log(response.status) // 500, 403, etc.4 console.log(response.data) // Response body5 },6})
Network errors
The onNetworkError callback fires when the request fails due to a network issue, such as when the user loses their internet connection. The callback receives the Error object.
1http.post('/api/users', {2 onNetworkError: (error) => {3 console.log(error.message)4 },5})1http.post('/api/users', {2 onNetworkError: (error) => {3 console.log(error.message)4 },5})
Precognition
The useHttp hook supports Laravel Precognition for real-time validation. Enable it by chaining withPrecognition() with the HTTP method and validation endpoint.
1import { useHttp } from '@inertiajs/vue3'23const http = useHttp({4 name: '',5 email: '',6}).withPrecognition('post', '/api/users')1import { useHttp } from '@inertiajs/vue3'23const http = useHttp({4 name: '',5 email: '',6}).withPrecognition('post', '/api/users')
1import { useHttp } from '@inertiajs/react'23const http = useHttp({4 name: '',5 email: '',6}).withPrecognition('post', '/api/users')1import { useHttp } from '@inertiajs/react'23const http = useHttp({4 name: '',5 email: '',6}).withPrecognition('post', '/api/users')
1import { useHttp } from '@inertiajs/svelte'23const http = useHttp({4 name: '',5 email: '',6}).withPrecognition('post', '/api/users')1import { useHttp } from '@inertiajs/svelte'23const http = useHttp({4 name: '',5 email: '',6}).withPrecognition('post', '/api/users')
Once enabled, the validate(), touch(), touched(), valid(), and invalid() methods become available, working identically to form precognition.
History State
You may persist data and errors in browser history state by providing a remember key as the first argument.
1const http = useHttp('SearchData', {2 query: '',3})1const http = useHttp('SearchData', {2 query: '',3})
1const http = useHttp('SearchData', {2 query: '',3})1const http = useHttp('SearchData', {2 query: '',3})
1const http = useHttp('SearchData', {2 query: '',3})1const http = useHttp('SearchData', {2 query: '',3})
You may exclude sensitive fields from being stored in history state using the dontRemember() method.
1const http = useHttp('Login', {2 email: '',3 token: '',4}).dontRemember('token')1const http = useHttp('Login', {2 email: '',3 token: '',4}).dontRemember('token')