vuejs / composition-api

Composition API plugin for Vue 2
https://composition-api.vuejs.org/
MIT License
4.19k stars 343 forks source link

Documentation for watchEffect is not correct #995

Closed craigcrawfordcts closed 1 week ago

craigcrawfordcts commented 1 week ago

The documentation stored here: https://vuejs.org/guide/essentials/watchers.html#watcheffect

Suggests that watchEffect can be used in place of watch.

However this is not the case because watchEffect callback does not support a Promise<void> return so TS will not allow compilation.

If the page is saved while debugging, and the props have not changed, with watchEffect the function that is supposedly "watched" automatically even though nothing has changed. The same does not happen with watch.

For example take the example store.ts: https://gist.github.com/craigcrawfordcts/f4923edf768a01b11c9a055acf96f20a

const props = defineProps<{
  id: string,
  branding?: string | undefined
}>();

const myStore = useMyStore();

The following works, and does not re-fetch if you attempt to re-save the file but the props have not changed:

watch(props, async (value, oldValue) => {
  if (value.id !== oldValue.id || value.branding !== oldValue.branding ) 
    await myStore.fetcher(props.id, props.branding);
});

However, none of the following work with watchEffect because it does not support Promises.

In this first example, the function is called every time I save a change in a vue file, but the above does not re-call it:

watchEffect(() => {
  myStore.fetcher(props.id, props.branding);
});

This also does not work, as TS doesn't like the Promise<void> return:

watchEffect(() => 
  myStore.fetcher(props.id, props.branding)
);

Can't use await since it's not an async, also not valid:

watchEffect(() => 
  await myStore.fetcher(props.id, props.branding)
);

So what if we make it an async?

watchEffect(async () => 
  await myStore.fetcher(props.id, props.branding)
);

Nope... Only watch works. So how do we make watchEffect automagically watch our props as the documentation states?