Reputation: 139
I am quite new in React.js and I have trouble with assigning my state through a static function call from another class. This code:
componentDidMount() {
this.setState(() => ({ movies: MovieService.getMovies() }));
}
Does not set my state. I believe the problem lies in my usage of the asynchronous function since if I use console.log(MovieService.getMovies())
, It shows Promise {<pending>}
. However, I am still confused on how to fix this, thank you for the help!
Upvotes: 1
Views: 158
Reputation: 2366
componentDidMount() {
MovieService.getMovies().then(moviesList => {
this.setState({ movies: moviesList }));
})
}
Assuming getMovies
returns a list of movies, you need to wait for the promise it returns to fulfil and then assign the value to your state
Upvotes: 4
Reputation: 30360
Your code will be setting the movies
field of your state to a Promise object representing the pending promise returned from the call to MovieService.getMovies()
Try making the following adjustment to your code to resolve the issue, by first resolving the promise and then assigning the result to your components state:
componentDidMount() {
MovieService.getMovies().then((movies) => {
this.setState({ movies: movies });
})
}
Upvotes: 3