Composition-api: Watched Previous Values can't be Destructure on First Fire

Created on 30 Jun 2020  路  7Comments  路  Source: vuejs/composition-api

When? watching an array of values I can't destructure the previous values on the initial loop run.
Why? the previous values are returned as undefined.
What I expect? I expect the previousValue on initial run to be equal to [undefined, undefined] so I can destructure it properly.

Code I have to write:

watch(
  () => [unref(unitId), unref(entityType)],
  ([newUnitId, newEntityType], oldValues) => {
    const [oldUnitId, oldEntityType] = oldValues || [undefined, undefined]

    if (!newUnitId || !newEntityType) return
    if (
      entitySchemaState.entitySchema &&
      newUnitId === oldUnitId &&
      newEntityType === oldEntityType
    )
      return

    fetch()
  },
  { immediate: true }
)

Code I want to write:

watch(
  () => [unref(unitId), unref(entityType)],
  ([newUnitId, newEntityType], [oldUnitId, oldEntityType]) => {
    if (!newUnitId || !newEntityType) return
    if (
      entitySchemaState.entitySchema &&
      newUnitId === oldUnitId &&
      newEntityType === oldEntityType
    )
      return

    fetch()
  },
  { immediate: true }
)
misalignment

Most helpful comment

I will have a look

All 7 comments

That's the same behaviour as you have in vue3.

AFAIK this is the expected behaviour since you are deconstructing an undefined.

@klondikemarlen This should work for you

watch(
  [unitId, entityType],
  ([newUnitId, newEntityType], [oldUnitId, oldEntityType]) => {

  }
)

Hope it solves your problem. Closing for now.

I know that I can't destructure an undefined. :P

I want the watch function to _always_ return an array if it is operating on an array of args.

@klondikemarlen This should work for you

watch(
  [unitId, entityType],
  ([newUnitId, newEntityType], [oldUnitId, oldEntityType]) => {

  }
)

When I try passing in an array instead of a function, I get the same destructuring error.
image

I will have a look

If this is expected behaviour, then I suggest updating the documentation to make it more clear. It is a bit confusing to get an error after using the 'Watching Multiple Sources'-example.

Was this page helpful?
0 / 5 - 0 ratings