Reputation: 35
I'm trying to push an object into a response from a axios get request, but i always got an 'push is not a function' error
i'm trying to push inside the .then block of the http request
ps: i'm following the example from the vuejs site
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
bitCoinValue: null
},
mounted() {
this.getBitcoinValue();
},
filters: {
currencydecimal(value) {
return value.toFixed(2);
}
},
methods: {
getBitcoinValue: function () {
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => {
this.bitCoinValue = response.data.bpi || [];
this.bitCoinValue.push({code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50});
});
}
}
})
this is the error message:
Uncaught (in promise) TypeError: this.bitCoinValue.push is not a function at site.js:21
Upvotes: 2
Views: 188
Reputation: 3731
the problem is that your response from https://api.coindesk.com/v1/bpi/currentprice.json
the bpi
entry is a Object
therefore you can not use push
because it is a function for the Array Object
.
you have 2 options:
set your value as the similar approach that the api responds
getBitcoinValue: function () {
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => {
this.bitCoinValue = response.data.bpi || [];
this.bitCoinValue['BRL'] = {code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50};
});
}
convert the object to array then push
getBitcoinValue: function () {
axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => {
let objectResponse = response.data.bpi || {};
this.bitconValue = Object.values(objectResponse).map(item => item)
this.bitCoinValue['BRL'] = {code: 'BRL', description: 'Reais', symbol: 'R$', rate_float: 25.50};
});
}
Upvotes: 1
Reputation: 686
Openig your API endpoint in a browser, I found out that the "bpi"
key in the response JSON is not an array but rather an object. So, instead of .push()
ing a value, you need to set the key directly, i.e. this.bitCoinValue.BRL = {...};
.
Upvotes: 1