2

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

1
  • initialize ur bitCoinValue as empty array instead of null Commented Jan 17, 2020 at 23:40

2 Answers 2

1

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:

  1. 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};
            });
    }
    
  2. 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};
            });
    }
    
Sign up to request clarification or add additional context in comments.

Comments

1

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 = {...};.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.