dcranmer's avatar

How to debounce text input when using Inertia's useForm()?

I have a page that does a filtered search using Laravel, Vue 3, and Inertia. All of the inputs are contained within Inertia's useForm.

const form = useForm({
  areas: null,
  county: null,
  school: null,
  search: null
})

I want to use debounce the submit method only on the search input, which the user types in (e.g., debounce(submit, 500) ). The other inputs are checkboxes and selects. All of the inputs are bound to form with v-model.

A watcher doesn't work here because (I think) useForm creates a reactive object (which I don't completely understand, but no matter). Does anyone have a suggestion on how to accomplish this?

0 likes
3 replies
LaryAI's avatar
Level 58

To debounce the submit method only on the search input when using Inertia's useForm(), you can use a computed property along with the lodash debounce function.

Here's an example of how you can achieve this:

import { useForm } from '@inertiajs/inertia-vue3'
import { debounce } from 'lodash'

export default {
  setup() {
    const form = useForm({
      areas: null,
      county: null,
      school: null,
      search: null
    })

    const debouncedSubmit = debounce(() => {
      form.submit()
    }, 500)

    return {
      form,
      debouncedSubmit
    }
  }
}

In this solution, we import the useForm function from @inertiajs/inertia-vue3 and the debounce function from lodash. We then create a computed property called debouncedSubmit that wraps the form.submit() method with the debounce function, specifying a delay of 500 milliseconds.

Now, you can use debouncedSubmit as the submit method in your template:

<template>
  <div>
    <input type="text" v-model="form.search" @input="debouncedSubmit" />
    <!-- Other inputs -->
  </div>
</template>

By using @input="debouncedSubmit", the debouncedSubmit method will be called only after the user has finished typing for 500 milliseconds. This effectively debounces the submit action on the search input.

Note: Make sure to install lodash by running npm install lodash or yarn add lodash before using the debounce function.

danielcoimbra's avatar

@pweil

I've created a reusable composable for this, considering pagination, etc...

It's been used in Modular and you can find the mentioned Composable here.

In this example instead of Lodash, I'm using "useDebounceFn" from Vue Use.

Hope it helps.

2 likes

Please or to participate in this conversation.