DEV Community

ktr92
ktr92

Posted on • Edited on

2

[vue3] Why is the length of a reactive Array always undefined?

I once spent a lot of time due to my superficial knowledge of Vue reactivity. I saw it very clearly and simply, but I never really thought about how it works.

For example, we have an empty array of strings that will be filled after user actions.

const inputData = ref<string[]>([])
Enter fullscreen mode Exit fullscreen mode

You'll always use ref() for primitives, but ref() is good for objects that need to be reassigned, like an array.

After the user's action and filling the array, we need to show him some information in the template, but before that it was hidden. So we add a computed property to keep track of the length of the array.

const inputLength = computed(() => {
  return inputData.value.length
})
Enter fullscreen mode Exit fullscreen mode
<template v-if="inputLength ">
 some information
</template>
Enter fullscreen mode Exit fullscreen mode

Problem:
At first glance this seems correct (to me), but it doesn't work because since we're using ref, our inputData is not an array of strings, but a ref object that has one property value. And inputData.value is also not an array of strings, but a proxy object.
So our inputLength computed property is always undefined.
For a long time I could not understand what was wrong here.

All we need to do is use Object.keys and get the number of keys of the proxy object.

Solution:

const inputLength = computed(() => {
  return Object.keys(inputData.value).length
})
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
panda_codes_3757bdd734894 profile image
Panda Codes

That's an interesting post but you might want to take a closer look at what you were doing. A reactive variable certainly does have a length property when its an array because calling .length on the proxy calls .length on the underlying array.

You can see it works perfectly fine here:
codepen.io/panda-writes-code/pen/Y...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay