Consider the following code:
const photos = reactive([]); // console.log(photos.value); // undefined (why?)
(async () => {
await fetch("https://jsonplaceholder.typicode.com/photos")
.then(response => response.json())
.then(json => { photos.value = json });
})();
const numPhotos = computed(() => photos.value?.length || 0);
/*
above is workaround instead of "computed(() => photos.value.length)"
which fails because photos.value is undefined
*/
I would like to code my computed as it is in the comment below my workaround. However the workaround is necessary because photos.value
is undefined. I understand fully well that the API call is asyncrhonous and so the array may not be fully populated when the computed is first used, but photos
was initialized with the empty array []
and that is what I would expect it's (necessary?) .value
attribute to return.
Am I misunderstanding the use of .value
. Or is an approach other than the work-around I've given?
Let me know if I can clarify anything.