Thought I understood .value but apparently not! 🙂
This is using VueJS v3 and Composition API. I’m attempting to find the first matching value in a reactive array of people. In reality my array is populated by an API call but the below has an equivalent hard-coded array. I also have a selectedPerson object which is used as a property to a component.
const people = ref([
{
id: 1,
name: 'Alice'
},
{
id: 2,
name: 'Bob'
},
{
id: 3,
name: 'Eve'
},
])
const selectedPerson = ref();
I then elsewhere want to find the one that matches and set it as the value for selectedPerson. Something like this:
function selectPerson(id) {
selectedPerson.value = people.value.find((person) => {person.id == id})
}
To my understanding value would return an actual array and I could use array functions such as find, match, filter on it. However, the right hand side of the assignment evaluates to undefined
.
Is it possible to use find on an array wrapped in a VueJS reactive object? What am I doing wrong? Or do I write my own loop for this? Many thanks for any help.
1
The problem here is in the syntax
selectedPerson.value = people.value.find((person) => {person.id == id})
is not returning anything, it should be :
selectedPerson.value = people.value.find((person) => {return person.id == id})
or simply selectedPerson.value = people.value.find((person) => person.id == id)
You can read more about it here.