Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch triggers on unmount for computed properties with undefined instead of the actual value #1525

Closed
posva opened this issue Jul 6, 2020 · 2 comments

Comments

@posva
Copy link
Member

posva commented Jul 6, 2020

Version

3.0.0-beta.18

Reproduction link

https://jsfiddle.net/82xpeomh/

Steps to reproduce

  1. Click on Toggle
  2. Look at the list or the console

What is expected?

When toggling the component the watcher should either provide the newest value or not trigger

What is actually happening?

it is providing undefined


This happens when the computed needs to be recalculated right when leaving, that's why there is a onBeforeUnmount. From vuejs/router#350

@Jack97
Copy link
Contributor

Jack97 commented Jul 6, 2020

I've had a quick look at this one and the culprit seems to be in the following lines of code:

https://github.com/vuejs/vue-next/blob/6dd59ee301d8d93e7ca14447243d07a653e69159/packages/runtime-core/src/renderer.ts#L1994-L2003

I commented out the stop effect loop, and the watcher was triggered with the correct new value. I also tried invoking the beforeUnmount hook after the stop effect loop, which stopped the watcher being triggered.

Hope this helps.

@johnsoncodehk
Copy link
Member

I think not trigger is the correct way. This is also the way of vue2.

This is an example, in response to the url parameter call api to get the page data, the code in the case of not trigger is:

// not trigger
setup() {
  const data = ref();

  watch(
    () => $route.query.dataId,
    async () => data.value = await fetchData($route.query.dataId),
    { immediate: true },
  )

  return { data };
}

If the trigger last value will require extra code to avoid triggering a useless api calling when leaving the page:

// trigger last value
setup() {
  const data = ref();
  let isOnBeforeUnmount = false;

  watch(
    () => $route.query.dataId,
    async () => {
      if (isOnBeforeUnmount) return; // getCurrentInstance().isUnmounted is false at last trigger
      data.value = await fetchData($route.query.dataId);
    },
    { immediate: true },
  )
  onBeforeUnmount(() => {
    isOnBeforeUnmount = true;
  });

  return { data };
}

@github-actions github-actions bot locked and limited conversation to collaborators Nov 9, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants