1

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=2626c70d&app_key=0c0f87ae4e5437621363ecf8e7ea80ae&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}
        />

Submitted July 18th 2021 by Admin

Answers
0

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

Try this

Admin | 2 months ago



Relevant Questions