kirimi
kirimi

Reputation: 1400

react-native fetch api arrays

I am trying to fetch facebook movie data using axios. In my console, I see the fetched data, but I have trouble getting when I want to access the title text.

 class BoardScreen extends Component {

      constructor(props) {
         super(props);
         this.state = { movies: [] };
      }

        componentWillMount() {
          axios.get('https://facebook.github.io/react-native/movies.json')
            .then(response => this.setState({ movies: response.data }));
        }

renderMovies() {
return this.state.movies.movies.map(movies => <Text>{movies.title}</Text>)
}

      render() {
if(this.state.movies.length === 0) {
     return null;
   }
        console.log(this.state.movies.title, 'movies')

        return (
          <View>
          {this.renderMovies()}
          </View>
                )
              }
            }

The code above only will give me the main title text The Basics - Networking What I really want is to access to each movie title and display.

How could I fetch each array title?

Upvotes: 4

Views: 3264

Answers (3)

Patel Dhara
Patel Dhara

Reputation: 886

add return statement in renderMovie() method.

renderMovie() {
  return this.state.movies.movies.map(movies => {
 return <Text>{movies.title}</Text>
})
}

Upvotes: 1

Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13787

class BoardScreen extends Component {

    constructor(props) {
        super(props);
        this.state = { movies: [] };
    }

    componentWillMount() {
        axios.get('https://facebook.github.io/react-native/movies.json')
        .then(response => this.setState({ movies: response.data }));
    }

    render() {
        return (
            <View>
                this.state.movies.movies.map((movie) =>
                    < Text key={movies.id}>
                        {movie.title}
                    </Text>
                );
            </View>
        )
    }
}

Upvotes: 0

Just code
Just code

Reputation: 13801

What you need is this looping through it and bind the data.

this.state.movies.movies.map(a=>{
           return <div key={a.id}>{a.title}</div>
        })       

Ofcourse you need to check if movies is not null, so render should look like this

  render() {

    if(this.state.movies.length === 0) {
      return null;
    }
    console.log(this.state.movies.movies, 'movies');

    return (
        this.state.movies.movies.map(a=>{
           return <div key={a.id}>{a.title}</div>
        })       

    )
  }

Demo

IMO, would be be very very easy if you just have looked here

Upvotes: 4

Related Questions