Onyx
Onyx

Reputation: 5782

Populating Vue data based on response from axios GET request

Imagine I make a GET request to an API endpoint that will return 10 images like this:

export default {
    data: function() {
        return {
            images: []
        }
    },
    mounted() {
        axios.get('https://api.unsplash.com/photos/?client_id=secret')
        .then(response => {
            for (var i = 0; i < response.data.length; i++) {
                this.images.push(response.data[i]);
            }
        })
        .catch((error) => console.log(error));
    }
}

Do I have to initialize an empty images array and then populate it with the response using a for loop like I have done in my code, or is that unnecessary? I can't really think of any other way to loop through the returned images unless I actually store them myself in my own variable.

Upvotes: 0

Views: 810

Answers (1)

Potato Salad
Potato Salad

Reputation: 4650

I don't see anything wrong with this. It's much cleaner to just assign it though, since you're only getting the images once in the mounted hook.

export default {
    data: function() {
        return {
            images: []
        }
    },
    mounted() {
        axios.get('https://api.unsplash.com/photos/?client_id=secret')
        .then(response => {
            this.images = response.data;
        })
        .catch((error) => console.log(error));
    }
}

Upvotes: 3

Related Questions