Reputation: 1512
I want to fetch an array of movies in the moviedb api. Based on the api parameters, there's only 10-12 elements in the api object so if I console log the returning movies data, I should only see an object with that many elements as soon as the application is loaded. But instead, the app makes an endless request and seems to be concatenating an empty object one request after another. Why isn't it requesting only once even though I've only made renderMovies() method call just once?
movie_list.js (Container)
class MovieList extends Component {
renderMovies() {
this.props.fetchMovies()
console.log(this.props.movies)
//console.log('hitting multiple times')
}
render() {
this.renderMovies()
return (
<div>Hello</div>
);
}
}
function mapStateToProps(state) {
return {
'movies': state.fetchMovies
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ 'fetchMovies': fetchMovies }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(MovieList);
Action Creator
import { FETCH_MOVIES } from '../actions/index';
export default function(state = [], action) {
switch (action.type) {
case FETCH_MOVIES:
return state.concat([action.payload.data])
}
return state;
}
Reducer Index
import { combineReducers } from 'redux';
import MovieReducer from './movie_reducer';
const rootReducer = combineReducers({
'fetchMovies': MovieReducer
});
export default rootReducer;
Reducer
import axios from 'axios';
export const FETCH_MOVIES = 'FETCH_MOVIES';
const API_KEY = '2458c1d252003392f870911dc14151e7';
const ROOT_API = `https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}`;
export function fetchMovies(){
const url = `${ROOT_API}&page=1`
const request = axios.get(url)
return {
'type': FETCH_MOVIES,
'payload': request
};
}
Here's a sample of console output
Upvotes: 0
Views: 301
Reputation: 2339
You're fetching your data inside a render function. Render is called whenever props changes, so your app does an initial render, gets the movies, which changes the state, which causes a render... put your fetch inside the componentDidMount lifecycle method to prevent this.
class MovieList extends Component {
componentDidMount() {
this.props.fetchMovies()
}
renderMovies() {
console.log(this.props.movies)
//console.log('hitting multiple times')
}
render() {
this.renderMovies()
return (
<div>Hello</div>
);
}
}
function mapStateToProps(state) {
return {
'movies': state.fetchMovies
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ 'fetchMovies': fetchMovies }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(MovieList);
Upvotes: 1