newVal and oldVal always the same when watching for Pinia state changes

Viewed 19

For some reason, when watching for Pinia state changes, the newVal and oldVal in the watch function are always identical (except for the very first time).

This is how my code looks like:

const { searchFilters } = storeToRefs(searchFiltersStore)

watch(searchFilters.value.categories, (newVal, oldVal) => {
  if (
    newVal.length !== oldVal.length ||
    newVal.every((value, index) => value !== oldVal[index])
  ) {
    reset(undefined, true)
  }
}, { deep: true })

searchFilters.value.categories are string[] (array made of strings) type and initially is an empty array.

When the first change is triggered, the oldVal is an empty array and the newVal is whatever it supposed to be. But after that, every new trigger has oldVal the same as newVal therefore, my if statement is never valid.

What am I missing?

1 Answers

I found that in order to watch an array, you have to pass a copy of the array and not the existing array like so:

watch(() => [...searchFilters.value.categories], (newVal, oldVal) => {
      ...
});

Also, the deep parameter in my case was not necessary.

Related