Julianv46
Julianv46

Reputation: 56

Rendering List with Fetch in React

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

Upvotes: 3

Views: 18985

Answers (3)

Igor Buts
Igor Buts

Reputation: 55

Gotten your movies in state you can do the next to render the list of movies:

render() {
  return (
    <h1>Movie List</h1>
    <ul>
      {
        this.state.movies.map((movie) =>
          <li key={movie}>movie</li>
        )
      }
    </ul>
  );
}

Upvotes: 0

Thomas Hennes
Thomas Hennes

Reputation: 9959

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>
  );
}

Upvotes: 2

djfdev
djfdev

Reputation: 6037

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>
    )
  }
}

Upvotes: 9

Related Questions