Subscribe on changes!

watchEffect can't track async reactive value

avatar
Sep 10th 2020

Version

3.0.0-rc.10

Reproduction link

https://codepen.io/zenheart/pen/jOqzZwV

Steps to reproduce

  1. click button
  2. wachtEffect will not track count change, because reactive value track in async operation.

What is expected?

make watchEffect has an async operation, also can track the reactive value

What is actually happening?

watchEffect can't track reactive value in async operation

avatar
Sep 10th 2020

This is expected, it's necessary for the watcher to collect dependencies synchronously. As you mentioned, you can still read properties outside of the asynchronous code (or before an await) to make it work. Maybe worth documenting in the API, will share with the team

avatar
Oct 23rd 2020

Small side effect of this: you can use an await to avoid a dependency to be tracked.

I had this situation where a watchEffect needed to use 3 reactive refs, but track only 2 of them. watch shall be used in these cases, but leveraging this behaviour you can actually filter which dependency to track (eg. adding an await for a nextTick or an immediate-resolving setTimeout).

In the following example, thirdProp won't be tracked, because it's accessed after await nextTick().

const myReactiveObject = reactive({
  firstProp: '',
  secondProp: '',
  thirdProp: ''
});

watchEffect(async () => {
      const { firstProp, secondProp } = myReactiveObject;

      await nextTick();
      myRef.value = await fetchData({
        firstProp,
        secondProp,
        thirdProp: myReactiveObject.thirdProp,
      });
    });

I then decided to use watch to avoid future clarity problems, as this is an hack anyway. But this limitation is worth a note somewhere in the docs