1

I'm making a Ajax request to a Json file that return some movies.

    state = { movies: [] };

    componentWillMount()
    {
        this.getMovies();
    }

    /*
       Make an ajax call and put the results in the movies array
     */
    getMovies()
    {
        axios.get('https://pastebin.com/raw/FF6Vec6B')
            .then(response => this.setState({ movies: response.data }));
    }



    /*
        Render every movie as a button
     */
    renderMovies()
    {
        const { navigate } = this.props.navigation;

        return this.state.movies.map(movie =>
            <ListItem key={ movie.title }
                title={ movie.title }
                icon={{ name: 'home' }}
                onPress={() =>
                    navigate('Details', { title: movie.title, release: movie.releaseYear })
                }
            />
        );
    }

    render() {
        return(
            <List>
                { this.renderMovies() }
            </List>
        );
    }

The error I get is the following: this.state.map is not a function. This is because movies is still empty.

When I console.log response.data it returns all the rows from the JSON file. So the problem is most likely in this line:

.then(response => this.setState({ movies: response.data }));

Does someone know what's wrong?

Nieck
  • 1,626
  • 3
  • 21
  • 41

2 Answers2

0

You put initial state in the wrong place. Do this instead:

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

From document:

In general, you should initialize state in the constructor, and then call setState when you want to change it.

Val
  • 21,938
  • 10
  • 68
  • 86
-1

Update you ajax request as following:

/*
   Make an ajax call and put the results in the movies array
 */
getMovies()
{
    let self = this;
    axios.get('https://pastebin.com/raw/FF6Vec6B')
        .then(response => self.setState({ movies: response.data }));
}

Also, you can bind your function inside constructor as:

constructor(props){
  super(props);
  this.getMovies = this.getMovies.bind(this);
}
Rohan Kangale
  • 931
  • 4
  • 11
  • 29