VUE: how to use watch with vue get and set composition api

116 views Asked by At

I am trying to create a searchable table element where user can also search and filter the returned result. but i can't seem to get how to set the value in the computed property setter.

but I keep getting tons of errors like: RangeError: Maximum call stack size exceeded

import { watch } from "vue";
import { computed, ref, reactive } from "vue";
import { useStore } from "vuex";



const searchText = ref("");
watch(searchText, () => filterHistory());
const user = computed(() => store.getters["profile/getProfile"]);

const reversedHistory = computed({
  get() {
    return user.value.history.reverse();
  },
  set(value) {
    reversedHistory.value = value;
  },
});


const filterHistory = () => {
  let newHistory = reversedHistory.value.filter(
    (item) => searchText === item.person
  );
  rerturn newHistory
};
1

There are 1 answers

1
Estus Flask On

reversedHistory changes itself inside a setter, this results in recursion.

Considering that user history is expected to be used from store, it makes sense to have relevant Vuex getter like profile/getHistory.

It's generally incorrect to mutate read-only computed, as it can discard the changes on the next update.

Vuex state isn't supposed to be mutated outside a store, there's supposed to be an action or mutation.

It could be:

const reversedHistory = computed({
  get() {
    return store.getters["profile/getHistory"]).reverse();
  },
  set(value) {
    store.commit('profile/setHistory', value.reverse());
  },
});