Vue 3 watch being called before value is fully updated

1.2k Views Asked by At

I'm working on my first Vue 3 (and therefore vuex 4) app coming from a pretty solid Vue 2 background.

I have an component that is loading data via vuex actions, and then accessing the store via a returned value in setup()

  setup() {
    const store = useStore();
    const fancy = computed(() => store.state.fancy);
    return { fancy };
  },

fancy here is a deeply nested object, which I think might be important.

I then want to run a function based on whenever than value changes, so I have set up a watch in my mounted() lifecycle hook

 watch(
      this.fancy,
      (newValue) => {
        for (const spreadsheet in newValue) {
          console.log(Object.keys(newValue[spreadsheet].data))
          setTimeout(()=>{
            console.log(Object.keys(newValue[spreadsheet].data))
          },500)
          ...

I tried using the new onMounted() hook in setup and watchEffect and store.watch instead, but I could not get watch/watchEffect to reliably trigger in the onMounted hook, and watchEffect never seemed to update based on my computed store value. If you have insight into this, that would be handy.

My real issue though is that my watcher gets called seemingly before the value is updated. For instance my code logs out [] for the first set of keys, and then a half second later a full array. If it was some kind of progressive filling in of the data, then I would have expected the watcher to be called again, with a new newValue. I have also tried. all the permutations of flush, deep, and immediate on my watcher to no avail. nextTick()s also did not work. I think this must be related to my lack of understanding in the new reactivity changes, but I'm unsure how to get around it and adding in a random delay in my app seems obviously wrong.

Thank you.

0

There are 0 best solutions below