Why vue reactive variable update _value property instead of value property?

Viewed 25

So I am learning vue 3 with composition API and I want to change the .value property of a variable 'filteredProjects' from axios response like so...

const filteredProjects = ref(null)
onMounted(async () => {
  await api.get("/project").then(response => filteredProjects.value = response.data);
})
console.log(filteredProjects.value)

I tried console.log(filteredProjects.value) but it returned null, so I checked out the variable without .value property console.log(filteredProjects) and find out that the response data from API is being set on the _value property instead of .value. This is the console result

RefImpl {__v_isShallow: false, dep: undefined, __v_isRef: true, _rawValue: null, _value: null}
dep: Set(1) {ReactiveEffect}
__v_isRef: true
__v_isShallow: false
_rawValue: {data: Array(13), message: 'successfully get data'}
_value: Proxy {data: Array(13), message: 'successfully get data'}
value: (...)
[[Prototype]]: Object
1 Answers

You're doing an asynchronous call inside the mounted hook which will run after console.log(filteredProjects.value), you could watch the filteredProjects or add async to the setup hook and await the response:

import {ref,watch,onMounted} from 'vue';

const filteredProjects = ref(null)
onMounted(async () => {
  await api.get("/project").then(response => filteredProjects.value = response.data);
})

watch(filteredProjects ,()=>{
    console.log(filteredProjects.value)
})

or with script setup, no need to add async anywhere :

<script setup>
import {ref,watch} from 'vue';

const filteredProjects = ref(null)

 const res = await api.get("/project").
 filteredProjects.value = res.data;

 console.log(filteredProjects.value)

</script>
Related