Typeerror

Hi there,

i write following stuff in my component:
export default {
name: “Shop”,
data: () => ({
products: null,
}),
mounted () {
this.getProducts()
},
methods: {
getProducts: () => {
axios
.get(’/api/products’)
.then(response => {
console.log(response.data);
this.products = response.data
})
.catch(error => (console.log(error)));
}
}
}

When i run the website, in the console log i have the correct data array from response.data. But i got the error:
TypeError: Cannot set property ‘products’ of undefined
when i want to assign the response data to this.products

What do i wrong?

Cheers
Ralf

You’re misusing arrow functions.

This:

getProducts: () => {

should be:

getProducts () {

Otherwise the this value will be bound to the surrounding this value, which is undefined in this case.

See:

https://v3.vuejs.org/guide/data-methods.html#methods

You should avoid using arrow functions when defining methods , as that prevents Vue from binding the appropriate this value.

Please also see Using Syntax Highlighting in this forum, which explains how to post code so that it’s easier for others to read.

1 Like