Eugene Chefranov
Eugene Chefranov

Reputation: 171

Cannot read property variable of undefined. Where is a mistake?

I trying to get data from another site and add it to array and after that I want to use data in a select, but I get error:

TypeError: Cannot read property 'locationList' of undefined

data() {
    return {
        locationList: [{
            text: 'Default',
            value: 'none'
        }]
    }
}

I run function on Created

created() {
    this.getLocations()
}

Simple function which get data from another site via fetch

methods: {
    getLocations: function() {
        fetch('https://www.webpagetest.org/getLocations.php?f=json')
            .then(function(response) {
                if (response.status === 200) {
                    return response.json()
                } else {
                    throw response;
                }
            })
            .then(function(data) {
                var list = Object.entries(data.data).map(([k, v]) => ({
                    text: v.Label,
                    value: k
                }))
                this.locationList.push(list);
            })
            .catch(function(e) {
                console.log(e)
            });
    }
}

Where is my mistake? How will be correct?

Upvotes: 1

Views: 165

Answers (2)

ryuzeke
ryuzeke

Reputation: 100

If you use arrow functions instead, you don't need to create variable to access this. Instead, this from the outer context is available inside the arrow function.

getLocations: function() {
    fetch('https://www.webpagetest.org/getLocations.php?f=json')
        .then((response) => {
            if (response.status === 200) {
                return response.json()
            } else {
                throw response;
            }
        })
        .then((data) => {
            var list = Object.entries(data.data).map(([k, v]) => ({
                text: v.Label,
                value: k
            }))
            this.locationList.push(list);
        })
        .catch(function(e) {
            console.log(e)
        });
}

Upvotes: 3

Jakub A Suplicki
Jakub A Suplicki

Reputation: 4801

It seems to be the context of this issue.

In your getLocations() try adding this line before the fetch:

let vm = this

then inside your fetch function use:

vm.locationList.push(list); instead of this.locationList.push(list);

Hope it helps. Good luck.

Upvotes: 3

Related Questions