'fetching json api in vueJs log the results but renders nothing (I'm new with Vue)
I'm new in VueJs, actually coming from react, the problem I'm having is that when i fetch the data with an axios.get the console.log shows a succesfull response. But when I to iterate through the Array with v-for it renders nothing. It's quite important so it be super appreciated if you can tell me what im doing wrong or you have a suggestion. heres the code:
<SignUpForm />
<h1>Countries List</h1 >
<div v-for="country in countries" :key="country.name" >
<p>{{country.name}}</p>
</div>
</template>
<script>
import SignUpForm from "@/components/SignUpForm.vue";
import axios from 'axios'
export default{
name: 'SignUpView',
components:{
SignUpForm
},
data(){
return{
countries: []
}
},
async mounted() {
const {data} = await axios.get('https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json')
console.info(data)
this.countries = data
}
}
</script>
You can see that what I'm actuallt doing is the axios.get in the mounted(){} f(x), later I = the data to my empty Array declared in data(){}. => So I can iterate trough the json response with a v-for in a div.
Solution 1:[1]
Observations :
- countries list is a string and
v-for
is work if the input data is an array. - No. of objects in an array is
243
but this9251
is a count of characters in a string. - Also, if we will try to convert that into a JSON object via
JSON.parse()
gettingSyntaxError: Unexpected token n in JSON at position 6
.
new Vue({
el: "#app",
data: {
countries: []
},
methods: {
getData() {
var vm = this;
axios.get("https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json")
.then(function(response) {
console.log(typeof response.data); <---- string
console.log(response.data.length); <---- actual objects in an array is 243 but this 9251 is a count of characters in a string.
console.log(JSON.parse(response.data)); <---- SyntaxError: Unexpected token n in JSON at position 6
})
.catch(function(error) {
alert(error);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<div id="app">
<button @click="getData">Click to check Api response</button>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rohìt JÃndal |