I'm doing a little project for showing movies from an API (TMDb) using Vue Routers. So I have a component called 'MovieList' where I connect to the API.
This is my data:
data() {
return {
movies: []
}
}
These are my methods:
methods: {
getMovies: () => new Promise((resolve, reject)=> {
const url = `https://api.themoviedb.org/3/discover/movie?api_key=MyAPI`;
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText).results);
} else {
reject(Error(xhr.statusText));
}
}
xhr.send();
})
}
and my mounted:
mounted() {
this.getMovies().then(
result => get(result)
)
function get(result) {
result.forEach((el) => {
this.movies = el
})
}
}
So, what I want is that the obtained array equals the variable 'movies' declared in 'data'.
Here is a screenshot:
And this is the error I get in console:
MovieList.vue?ea6b:34 Uncaught (in promise) TypeError: Cannot set property 'movies' of undefined
at eval (MovieList.vue?ea6b:36)
at Array.forEach (<anonymous>)
at get (MovieList.vue?ea6b:35)
at eval (MovieList.vue?ea6b:30)
Thanks everyone, hope you can help me!