I’m trying to work with a movie API and send a request in a React program using the Axios library. I’m able to retrieve the data and console.log it but I’m struggling to map through the data and display it in a React component.
I used this example that makes a request to the Reddit API to base my approach off of:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from "axios";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
axios.get(`http://www.reddit.com/r/${this.props.subreddit}.json`)
.then(res => {
const posts = res.data.data.children.map(obj => obj.data);
this.setState({ posts });
});
}
render() {
return (
<div>
<h1>Top stores from Reddit/hockey</h1>
<ul>
{this.state.posts.map(post =>
<li key={post.id}>{post.title}</li>
)}
</ul>
</div>
);
}
}
ReactDOM.render(
<App subreddit="hockey"/>,
document.getElementById('render-target')
);
This works and fetches the Reddit API. I’m trying to modify it to work with the movie API I’m using, like this:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from "axios";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=03b9a40695aae1f4e99a42e90e012e9e&language=en-US&page=1`)
.then(res => {
const posts = res.data.results.map(obj => obj.data);
console.log(res.data.results[3].original_title);
this.setState({ posts });
});
}
render() {
return (
<div>
<h1>Movie API data</h1>
<ul>
{this.state.posts.map(post =>
<li key={post.id}>{post.title}</li>
)}
</ul>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('render-target')
);
I’m about to console.log the data but how can I map through the entire JSON response and map all the movies?