Salvo
Salvo

Reputation: 107

Fetch data from API using React Native

I'm trying to fetch data from the url below, but when I launch the code it returns the error: TypeError: undefined is not an object (evaluating 'res.data.hints'), and consequentially nothing happens, I've followed various tutorials and they seem to come up with this code.

States

constructor(props) {
    super(props);
    this.updateSearch();
    this.state = {
      data: [],
    };
  }

Function

 updateSearch = () => {
        const url = `https://api.edamam.com/api/food-database/v2/parser?ingr=b&app_id=000&app_key=00000&page=20`;
        fetch(url)
           .then((res) => res.json())
           .then((res) => {
             this.setState({
               data: res.data.hints
             });
           })
           .catch(error => {
            console.log("error : "+ error)
          });
      };

Flatlist

     <FlatList
          data={this.state.data}
          renderItem={({ item }) => (
            <ListItem>
              <TouchableOpacity>
                <View>
                  <Text>{item.label}</Text>
                  <Text>{item.brand}</Text>
                </View>
              </TouchableOpacity>
            </ListItem>
          )}
          keyExtractor={(item) => item.foodId}
        />

Upvotes: 1

Views: 261

Answers (1)

Adnan Samir
Adnan Samir

Reputation: 171

this.setState({
           data: res.hints
         });

Try this

Upvotes: 3

Related Questions