The issue you're encountering is due to how the debounce function from Lodash works. When you call debounce(search, 500) inside the watch callback, you're creating a new debounced function every time the searchString changes. This means that the debounced function is not retaining its state between calls, and thus, it never actually gets to the point where it executes the search function.
In your first example, you correctly create a single debounced function outside of the watch callback, which retains its state and works as expected. Here's a breakdown of why the second approach doesn't work and how to fix it:
Why the Second Approach Doesn't Work
-
New Debounced Function Each Time: Every time
searchStringchanges, a new debounced function is created. This new function has its own timer, which starts fresh each time, and thus, it never reaches the point where it executes thesearchfunction. -
State Retention: Debounced functions need to retain their state (like the timer) across multiple calls to work correctly. Creating a new debounced function each time prevents this.
Solution
To fix this, you should create the debounced function once, outside of the watch callback, and then call this debounced function inside the watch callback. Here's how you can do it:
// imports
import { ref, watch } from 'vue';
import debounce from 'lodash/debounce';
// search string
const searchString = ref('');
const searching = ref(false);
// search
const search = () => {
console.log('Searching with: ', searchString.value);
};
// Create a debounced version of the search function
const debouncedSearch = debounce(search, 500);
// watch search string
watch(searchString, () => {
console.log('Inside watch');
debouncedSearch();
});
Explanation
-
Debounced Function Creation: By creating
debouncedSearchoutside of the watch callback, you ensure that the same debounced function is used every timesearchStringchanges. This allows the debounce logic to work correctly, as it can maintain its internal state (like the timer) across multiple invocations.
This approach will ensure that your search function is debounced correctly, preventing it from being called too frequently as the user types.