Search code examples
javascriptvue.jsrich-text-editorcomputed-propertiestiptap

Vuejs, computed property with setter freeze component


I have a component with tiptap text editor. I use a computed property with a setter to bind data to the editor.

<template>
  <tiptap model="editNoteContent" extensions" />
</template>

<script>
export default {
  computed: {
    editNoteContent: {
      get() {
        return this.$store.state.Notes.currentNote.text;
      },
      set(text) {
        this.$store.commit("Notes/updateCurrentNoteText", text);
      },
    }
  },
}
</script>

When I type a lot of text fast, my component freezes. I use a computed property because I have to get some current text, and only then change it. Does somebody know best practice for situation like this? How can I solve this issue?


Solution

  • A common solution to this type of problem is to debounce the call, which delays the callback event. For example, you could debounce the mutation by using clearTimeout() to cancel any pending calls, and then setTimeout() to delay the $store.commit() call:

    export default {
      computed: {
        editNoteContent: {
          get() { /*...*/ },
          set(text) {
            // cancel pending commits, if any
            clearTimeout(this._timer)
    
            // commit newest text after 300ms
            this._timer = setTimeout(() => {
              this.$store.commit("Notes/updateCurrentNoteText", text)
            }, 300)
          }
        }
      }
    }