Rendering List with Fetch in React

14,326

Solution 1

A few things. fetch is asynchronous, so you're essentially just going to be setting movies to an empty array as this is written. If data is an array of movies, you can just set that directly in your state rather than copying it to a new array first. Finally, using an arrow function for the final callback in the promise will allow you to use this.setState without having to explicitly bind the function.

Finally, you can use JSX curly brace syntax to map over the movies in your state object, and render them as items in a list.

class MyComponent extends React.Component {
  constructor() {
    super()
    this.state = { movies: [] }
  }

  componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
      .then(response => response.json())
      .then(data => {
        this.setState({ movies: data })
      })
  }

  render() {
    return (
      <div>
        <h1>Movie List</h1>
        <ul>
          {this.state.movies.map(movie => {
            return <li key={`movie-${movie.id}`}>{movie.name}</li>
          })}
        </ul>
      </div>
    )
  }
}

Solution 2

First of all, since fetch is asynchronous, you will most likely call setState before the fetch call has completed, and you obviously don't want to do that.

Second, if the data returned is an array of movies, do not iterate over it, just assign the array altogether to the movies state variable.

So, in short, this is what your componentDidMount method should look like :

componentDidMount() {
  var myRequest = new Request(website);

  fetch(myRequest)
    .then(res => res.json())
    .then(movies =>
      this.setState({ movies }) // little bit of ES6 assignment magic 
    );
}

Then in your render function you can do something like:

render() {
  const { movies } = this.state.movies;
  return (
    <ul>
      { movies.length && movies.map(m => <li key={m.title}>{m.title}</li>) }
    </ul>
  );
}
Share:
14,326
Julianv46
Author by

Julianv46

Updated on June 23, 2022

Comments

  • Julianv46
    Julianv46 almost 2 years

    Trying to render a list of movies from a random API and eventually filter them.

    componentDidMount() {
        var myRequest = new Request(website);
        let movies = [];
    
        fetch(myRequest)
            .then(function(response) { return response.json(); })
            .then(function(data) {
                data.forEach(movie =>{
                    movies.push(movie.title);
                })
            });
         this.setState({movies: movies});
    }
    
    render() {
        console.log(this.state.movies);
        console.log(this.state.movies.length);
        return (
            <h1>Movie List</h1>
        )
    }
    

    If I render this I can only print my state and not access what is inside. How would I create a list of LIs and render a UL? Thanks

  • Julianv46
    Julianv46 over 6 years
    Thank you so much!