1

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
norbekoff
  • 1,719
  • 1
  • 10
  • 21
Fath-Likki
  • 35
  • 5
  • 1
    This is fine in Vue3. When you assign something to .value, it maps to _value and _rawValue as well – Amaarockz Sep 21 '22 at 07:22
  • Related, https://stackoverflow.com/questions/17546953/cant-access-object-property-even-though-it-shows-up-in-a-console-log?rq=1 . It's not specific to Vue, this is how JS works. Here the promise isn't chained correctly. – Estus Flask Sep 21 '22 at 07:36
  • put the console.log inside the onMounted – Jaromanda X Sep 21 '22 at 07:37

1 Answers1

1

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>
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164