Reusing Components in React

Reusing Components in React
0.0 0

#1

I am trying to render information from multiple URLs, using the OMDB API. I stored the URLs in an array, and I can pull up the desired information in the console. I want to render that information (title, genre, rating, etc.) for 10 different movies. I have only managed to render information for one movie at a time.

I think I should do this by reusing my MovieCard child component, and by mapping through the array of URLs, but I can’t get it to work.

I hope that makes sense! Thanks in advance.

//URLs for movie information
var movieArray = [
  'http://www.omdbapi.com/?t=up&apikey=de322a1c',
  'http://www.omdbapi.com/?t=ghostbusters&apikey=de322a1c',
  'http://www.omdbapi.com/?t=indiana+jones&apikey=de322a1c'
]

//Child component that I want to reuse on 10 different movies/URLs
class MovieCard extends Component{
	render(){
		return(
			<div >
			   <div id="card">
			      <h2 id="movieTitle">{this.props.title}</h2>
	           </div>
			</div>
		);
	}
}

//Parent component that also fetches the movie information (objects)
class App extends Component {

constructor(){
    super();
    this.state = {
      title: [],
    };
  }

//Use APIs to fetch the information.
//Objects for EACH movie appear in console, correctly.
componentDidMount() {

  for (var i = 0; i<=movieArray.length; i++){
    fetch(movieArray[i])
    .then(response=>response.json())
    .then(response =>{
        console.log(response)
        this.setState({
           title: response.Title,
       })
     })  
    .catch(error => console.log('parsing failed', error)) 
 }
}

  render() {
//I think I should use .map on movieArray here and store it as a variable

//This currently renders information from only one movie (understandably, the last one fetched above).
return (
<div className="App">
   <MovieCard title={this.state.title} />
 </div>
    );
  }
}

#2

Hey there, not 100% sure, but just from a cursory glance what I think you’re doing wrong here is in the fetch call you’re making.
You’re making multiple fetch calls using a for loop, but each time, you’re setting the LATEST response to your fetch to the ‘title’ state, instead of adding it to the state/pushing it to an array. As a result, state will always be set to the single response to the last url in your movieArray, instead of an array of all your responses.


#3

Also, a for loop is a synchronous operation, while a fetch() call is technically a Javascript Promise and asynchronous, so I’m not sure you’d likely achieve your intended results with a for loop either. I could be wrong, so take this with a grain of salt


#4

Thank you! I created an empty array inside of this.state, pushed the responses into that array, and then used .map in the render method. I have noticed that, since fetch() is asynchronous, the movies render in a different order each time.

Thanks again for your help!!