Reputation: 3508
I'm new to Vue and still learning the ropes. I currently am fetching data from an endpoint and it's returning an object. The object is successfully making it into the component (it's showing up in the devtools and on the page, see the p
tag in template
.) However, despite the fact that all the data is there, I have no idea how I am supposed to access the url property that exists on the info object. Everything I've tried so far has failed to work.
Here is the error message:
TypeError: Cannot read property 'url' of null
Is there some other approach or lifecycle method im supposed to use for async behaviors?
<template>
<div class="SpaceImage">
<img :src="info.url" />
<p>{{info}}</p>
</div>
</template>
<script>
import axios from "axios";
import { API_KEY } from "../../API_KEY/API_KEY";
export default {
name: "SpaceImage",
data() {
return {
info: {},
imnageData: ''
};
},
created() {
axios
.get(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`)
.then(response => (this.info = response))
.catch(error => console.log(error));
}
};
</script>
<style>
.SpaceImage {
border: 1px solid red;
height: 100px;
width: 100px;
}
img {
width: 100px;
height: 100px;
border: 1px solid blue;
}
</style>
Upvotes: 1
Views: 585
Reputation: 1092
Kevin!
There can be a few moments, related to your problem.
One is that @helikat_ sugggested, and the second is
.then(response => (this.info = response.data))
You need to get data
property from the response object. It contains the response content.
Upvotes: 2
Reputation: 493
You need to capture the this
value before your axios call.
created() {
const vm = this;
axios
.get(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`)
.then(response => (vm.info = response.data))
.catch(error => console.log(error));
}
Upvotes: 1