Usage of InertiaJS reactive forms
![Usage of InertiaJS reactive forms](https://www.adambiro.com/wp-content/uploads/2021/12/inertiaJS-768x384.png.webp)
InertiaJS reactive forms have three approaches to manage them.
InertiaJS form usage in general
- Original form approach
- It will work, but it reloads the page that violates the SPA approach.
- reactive approach
- form helper approach
- This approach has some inbuild things that we can use
To be able to use the reactive approach, we need to import the followings:
import { reactive } from 'vue'
import { Inertia } from '@inertiajs/inertia'
Udage of InertiaJS reactive forms
Two-way data binding is necessary to detect any change in the input fields, so we need the v-model directives in the form inputs.
<template>
<form @submit.prevent="submit">
<label for="first_name">First name:</label>
<input id="first_name" v-model="form.first_name" />
<label for="last_name">Last name:</label>
<input id="last_name" v-model="form.last_name" />
<label for="email">Email:</label>
<input id="email" v-model="form.email" />
<button type="submit">Submit</button>
</form>
</template>
Furthermore, to handle the form data, we need to define a correspondence form object that will store the form input information in an object.
let form = reactive({
first_name: null,
last_name: null,
email: null,
})
By the way, we do not want to manage the form in the ‘old’ way. So neither the action nor the method attribute on the form tag is necessary. But we need to prevent the default submission while calling our submit function to make the form post. Due to this, the @submit.prevent=submit attribute solves that problem by calling the method below:
let submit = () => {
Inertia.post('/users', form)
}
Let’s see the InertiaJS code in one place:
Worth noting:
The third parameter of the InertiaJS form method is the options param. This param can accept here callback hooks to make changes in the different states of the submission.
Inertia.post('/users', data, {
onBefore: (visit) => {},
onStart: (visit) => {},
onProgress: (progress) => {},
onSuccess: (page) => {},
onError: (errors) => {},
onCancel: () => {},
onFinish: visit => {},
})
Conclusion & Closing
Previously, I wrote a note about active link creation in InertiaJS. In this one, I have written about the reactive forms. So the next one is going to detail the form helper. It can make the usage of reactive forms easier.