Skip to content

useRouteQuery triggers reactivity twice #4112

@aethr

Description

@aethr

Describe the bug

When updating a ref created with useRouteQuery, trigger is called twice:

This doesn't appear to trigger watchers twice if watching the ref directly. This may be because vue isn't calling watchers if an equality check passes (old value === new value).

This is an issue if you create a computed with a non-scalar value using the value from the ref, like:

const foo = useRouteQuery('foo');
const bar = computed(() => ({ bar })); // gets re-created twice whenever foo is updated

In this case watchers will be called twice because the object created by the computed will not pass an equality check, even if all the inner values are the same.

This is also presumably an issue with useRouteParams and useRouteHash with both take a similar approach.

I will try to create a PR to fix this by applying the same check inside the watcher that's used in the setter:

  watch(
    () => route.query[name],
    (v) => {
        // add the same equality check to prevent unnecessary trigger
        if (query === v)
          return

      query = v

      _trigger()
    },
    { flush: 'sync' },
  )

Reproduction

https://codesandbox.io/s/async-silence-q52wwm?file=/src/views/Home.vue

System Info

System:
    OS: Linux 6.8 Ubuntu 24.04 LTS 24.04 LTS (Noble Numbat)
    CPU: (20) x64 13th Gen Intel(R) Core(TM) i7-13700H
    Memory: 9.01 GB / 31.02 GB
    Container: Yes
    Shell: 5.9 - /usr/bin/zsh
  Binaries:
    Node: 20.13.1 - ~/.nvm/versions/node/v20.13.1/bin/node
    npm: 10.5.2 - ~/.nvm/versions/node/v20.13.1/bin/npm
  Browsers:
    Chrome: 126.0.6478.126
  npmPackages:
    @vueuse/core: ^10.11.0 => 10.11.0
    @vueuse/router: ^10.11.0 => 10.11.0
    vue: ^3.4.27 => 3.4.31

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions