How to debounce a function in a watched property?
-
I have a function that sends data (
noteContent
) to an API.noteContent
is changed in a<textarea>
and I would like to send it to the API not more often than every 3 seconds.I tried the following code, but
saveNote()
is not called at all:<script> import {debounce} from 'quasar' export default { name: 'MainLayout', data() { return { (...) noteContent: '', noteFilename: '', (...) }, methods: { (...) saveNote() { fetch(`http://localhost:6543/write/${this.noteFilename}`, { method: 'POST', body: this.noteContent }) } }, watch: { noteContent: function () { debounce(this.saveNote, 3000) } } (...) } </script>
-
Try it like this:
<script> import {debounce} from 'quasar' export default { name: 'MainLayout', data() { return { (...) noteContent: '', noteFilename: '', (...) }, methods: { (...) saveNote() { fetch(`http://localhost:6543/write/${this.noteFilename}`, { method: 'POST', body: this.noteContent }) } }, watch: { noteContent: function () { this.debounceNoteContent() } }, created () { this.debounceNoteContent = debounce(this.saveNote, 3000) } (...) } </script>
Scott
-
Coming back to confirm that it works great this way. Thanks!