FlatList stays blank after getting data from API

Viewed 154
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.spoonacular.com/food/products/search?apiKey=1234&query=${value}&number=100`
        )
        .then((res) => {
          this.setState({ data: res.data });
        })
        .catch((error) => {
          console.log(error.response.data);
        });
    } else {
      setState({ data: [] });
    }
}}

  render() {
    const {
      data,
      searchValue,
    } = this.state;


    return (
          <SearchBar
            placeholder="Search Food..."
            onChangeText={this.updateSearch}
            value={searchValue}
            <FlatList
              data={this.state.data}
              renderItem={({ item }) => (
                  <Text>{item.products.title}</Text>
                      )}
              keyExtractor={item => item.id}
            />

Hey everyone, I'm trying to show the products of the API of Spoonacular in the Flatlist by searching in the SearchBar, no error are shown when I run the code, but the Flatlist just stays blank, what is wrong with it?

Link to documentation of the Database: https://spoonacular.com/food-api/docs#Search-Grocery-Products

1 Answers

The response data shape is

{
    "products": [
        {
            "id": 192386,
            "title": "Pizza Buddy: Frozen Pizza Dough, 16 Oz",
            "imageType": "jpg"
        },
        {
            "id": 27693,
            "title": "Uno Pizza",
            "imageType": "jpg"
        }
    ],
    "totalProducts": 1258,
    "type": "product",
    "offset": 0,
    "number": 2
}

products is the array that should be passed to the flatlist.

<FlatList
  data={this.state.data.products} // <-- pass the products array from state
  renderItem={({ item }) => (
    <Text>{item.title}</Text> // <-- it is just item.title
  )}
  keyExtractor={item => item.id}
/>

This would require this.state.data to be an object though, so it may be better to only update state with the products data.

updateSearch = (value) => {
  this.setState({ searchValue: value });
  if (value.trim() !== "") {
    axios
      .get(
        `https://api.spoonacular.com/food/products/search?apiKey=1234&query=${value}&number=100`
      )
      .then((res) => {
        this.setState({ data: res.data.products });
      })
      .catch((error) => {
        console.log(error.response.data);
      });
  } else {
    setState({ data: [] });
  }
}}

Then pass as usual

<FlatList
  data={this.state.data}
  renderItem={({ item }) => (
    <Text>{item.title}</Text> // <-- it is just item.title
  )}
  keyExtractor={item => item.id}
/>
Related