Skip to content

Option to not stop watch when component is unmounted #1532

Closed
@vmihailenco

Description

@vmihailenco

What problem does this feature solve?

I have a composition function that is shared between multiple components:

// global shared reactive state
let foo

function useFoo() {
  if (!foo) { // lazy initialization
      foo = ref()
      watch(foo, ...) // <- this is stopped when component that created it is unmounted
      // make some http calls etc
  }
  return foo
}

component1 = {
    setup() {
        useFoo() // lazily initialize
    }
}

component2 = {
    setup() {
        useFoo() // lazily initialize
    }
}

The problem is that watch is stopped when the component that called useFoo first is unmounted.

What does the proposed API look like?

An option for watch

watch(..., {instanceBound: false})

Or a helper that nulls the current instance:

function withNullInstance(cb: Function) {
    const old = getCurrentInstance()
    setCurrentInstance(null)
    cb()
    setCurrentInstance(old)
}

function useFoo() {
    if (!foo) {
        withNullInstance(initFoo)
    }
    return foo
}

Or export getCurrentInstance and setCurrentInstance so this can be solved in user space.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions