0
export class Diet extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: [],
      searchValue: "",
    };
  }
  updateSearch = (value) => {
    this.setState({ searchValue: value });
    if (value.trim() !== "") {
      axios
        .get(
          `https://api.edamam.com/api/food-database/v2/parser?ingr=${value}&app_id=2626c70d&app_key=0c0f87ae4e5437621363ecf8e7ea80ae`
        )
        .then((res) => {
          this.setState({ data: console.log(res.data.hints) });
        })
        .catch((error) => {
          console.log(error.response.data);
        });
    }
  };

return (
     <SearchBar
        placeholder="Search Food..."
        onChangeText={this.updateSearch}
        value={searchValue}
      />

     <FlatList
              style={{ paddingTop: hp("2%") }}
              data={this.state.data.map((item) => item.food)}
              renderItem={({ item }) => (
                <List>
                  <ListItem>
                    <Left>
                      <TouchableOpacity>
                        <Text>{item.label}</Text>
                      </TouchableOpacity>
                    </Left>
                    <Right>
                      <Icon
                        name="arrow-forward"
                        style={{ fontSize: 25, color: "red" }}
                      />
                    </Right>
                  </ListItem>
                </List>
              )}
              keyExtractor={(item) => item.foodId}
            />

Hi everyone, I'm trying to get data from the API of Edamam, I'm using a SearchBar to get the value the user is typing and show the list of the label of foods in the FlatList below, the URL works fine, when I run the code and I start typing the console.log returns 'undefined'.

Link to documentation: https://developer.edamam.com/food-database-api-docs

1 Answers1

0

From the docs, it looks like res.data.parsed returns an array. You should use res.data.parsed[0].food to get access to the parsed food item and res.data.hints to access the list of foods. I'm guessing you want to display the latter.

axios
  .get(
    `https://api.edamam.com/api/food-database/v2/parser?ingr=${value}&app_id=2626c70d&app_key=0c0f87ae4e5437621363ecf8e7ea80ae`
  )
  .then((res) => {
    this.setState({ data: res.data.hints })
  })
  .catch((error) => {
    console.log(error.response.data)
  })
<FlatList
  style={{ paddingTop: hp('2%') }}
  data={this.state.data.map((item) => item.food)}
  renderItem={({ item }) => (
    // ...
  )}
  keyExtractor={(item) => item.foodId}
/>

The renderItem function renders a list for every item which doesn't look right. You probably want to render a ListItem instead.

And you might want to debounce the input change handler. Check this answer for more information.

Arun Kumar Mohan
  • 11,517
  • 3
  • 23
  • 44
  • I ran your code, and the console returned the array correctly, but the app shows the following error: `undefined is not an object (evaluating 'this.state.data.map')` –  Mar 29 '21 at 03:32
  • @PiersalvoMigliore Looks like you're not setting the state properly. You should use `this.setState({ data: res.data.hints })`. – Arun Kumar Mohan Mar 29 '21 at 03:34
  • @PiersalvoMigliore As I mentioned in my previous comment, you're not setting the state right. `console.log` returns `undefined`. Refer to my previous comment or the answer above. – Arun Kumar Mohan Mar 29 '21 at 03:40
  • @PiersalvoMigliore Btw, please add your edits to a separate section in the question to make sure your original question and the initial version of the code remain visible (not everyone has the patience to dig into the revision history). With your current edits, the description and the code don't match at all. – Arun Kumar Mohan Mar 29 '21 at 03:51
  • Thanks, it worked, by the way it shows another error: `Warning: Encountered two children with the same key, `food_bmyxrshbfao9s1amjrvhoauob6mo`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.` is the problem the keyExtractor? –  Mar 29 '21 at 03:58
  • 1
    @PiersalvoMigliore Interesting. Looks like the API returns duplicate food items (items with the same `foodId` value). You could remove the duplicates before rendering the items. – Arun Kumar Mohan Mar 29 '21 at 04:00