Answer the question
In order to leave comments, you need to log in
Is React app sending a huge amount of fetch requests?
Good day. I'm just learning, I'm doing an educational project - "movie search" at the minimum using the movie db api.
By design, the application should send a get-request to the database via api, based on the response, render cards with movies. And in the prototype this happens, but the requests go in a continuous stream, which leads to brakes and is not necessary at all.
Due to inexperience and / or stupidity, I can’t imagine where the problem is - in the use of fetchAPI or in the logic as a whole?
class App extends React.Component {
constructor() {
super();
this.state = {};
}
fetchApi() {
fetch(URL)
.then(res => res.json())
.then(data => {
this.setState(data.results); //ответ записываем в стэйт
});}
render() {
this.fetchApi(); //посылаем запрос
return (
<div className="movie-list">
<MovieCard data={this.state} /> //выводим карточки с передачей стэйта в пропсы
</div>
);}
class MovieCard extends React.Component {
render() {
let data = this.props.data;
let movieItem = Object.values(data).map(element => element); //т.к. в ответ получаем объект с объектами, проходимся по нему
return movieItem.map(movie => ( //и еще раз, уже по объекту с данными о фильме
<div>
<h1>{movie.title}</h1>
<img
src={baseImgUrl + movie.poster_path}
alt={movie.original_title}
/>
<p>{movie.overview}</p>
</div>
))}}
Answer the question
In order to leave comments, you need to log in
1. In componentDidMount we make a request to api and save the result to the state.
2. In render, we get the result from this.state and loop through the movie cards.
3. If you need to load more cards, do it by clicking on the button. The click will cause fetch, the state will change, the cards will be drawn.
You have this.fetchApi() in each render, and in it you change the state, read at what point the render is performed
1) Read about the life cycle
https://reactjs.org/docs/state-and-lifecycle.html
3) On future read about redux + (redux-thunk or redux-saga)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question