Riza Khan
Riza Khan

Reputation: 3158

VUE 3 - watch not returning correct values

In a Vue 3 app, I am referencing store getter and watching the change in its value to do some logic.

I need to compare the old and new values. However, I am getting the same values for each argument passed to the watch function.

Here is my setup:

<script>
import { useStore } from 'vuex'
import { watch } from 'vue'

export default {
  setup() {
    const store = useStore()
    let text = store.getters['SOME_ARRAY']
    
    watch(text, (text, prevText) => {
      console.log(text.length, prevText.length)
    })    
  }

   return { text }
}

</script>

In the console.log both lenghts are the same (ie, 3 3, 4 4, 5 5...).

Upvotes: 4

Views: 627

Answers (2)

tony19
tony19

Reputation: 138576

text should use computed on the getter, so that its reference in the watch is kept up to date:

// let text = store.getters['SOME_ARRAY']
let text = computed(() => store.getters['SOME_ARRAY']) ✅

demo

Upvotes: 1

aligumustosun
aligumustosun

Reputation: 152

Can you try this?

store.watch(() => store.getters['SOME_ARRAY'], (oldValue, newValue) => {
  console.log(oldValue)
  console.log(newValue)
})

Upvotes: 0

Related Questions