You simply check your data with the console.log()
before it is loaded.
UPDATE
The playground demonstrates the problem you have.
- Data property is defined
const data = ref(null);
- Axios request is started
- The current value of the data property is logged and it is equals
null
, since the request is not yet done.
- Request is done and the data property is filled with the request data.
So, you are trying to get the value from the data property, before the axios request is done. That's why the console.log(data.value);
logs 'null'.
The playground does not really provide a solution for the problem. If you want to process the data right after it's loaded, then you should use Promises
or async/await
.
If you want to watch your data property and react to data changes, then create a watcher
.
watch(() => data.value...., (val) => {....})
UPDATE 2
If you want to log your data after the request is done, then put the console.log(data.value)
into .then()
.then((res) => {
data.value = res.data;
console.log(data.value)
})
To use the data, you have to wait till it is loaded. You can do it in several ways.
For example, you could watch the isLoaded
property.
in useAxiosGet.js
const isLoaded = ref(false);
and
.then((res) => {
data.value = res.data;
isLoaded.value = true;
})
and watcher for isLoaded
watch(() => isLoaded.value, () => useMyData(data))
I have updated the playground with the watcher
const { createApp, ref, watch, watchEffect, isRef } = Vue;
const useAxiosGet = (url) => {
const data = ref(null);
const isLoaded = ref(false);
watchEffect(async () => {
axios({
url: url
})
.then((res) => {
data.value = res.data;
isLoaded.value = true;
})
.catch((err) => console.log(err));
});
watch(() => isLoaded.value, () => console.log(data.value))
return { data, isLoaded };
}
const app = createApp({
setup () {
const { data } = useAxiosGet('https://jsonplaceholder.typicode.com/todos/1');
console.log(data); // logs the usual wrapper around refs, where i find my data under '_rawValue'.
console.log(isRef(data)) // logs a true - the object didnt lose reactivity while destructuring.
console.log(data.value); // logs 'null'.
const logData = () => console.log(data.value);
return { data, logData }
}
})
app.mount('#app')
<div id="app">
data: {{ data }}<br/>
<button @click="logData()">log</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>