0
export class Diet extends Component {
  constructor(props) {
    super(props);
    this.state = {
          data: [],
         };
  }
 updateSearch = (e) => {
    axios
      .get(
        `https://api.spoonacular.com/food/products/search?apiKey{1234}&number=100`
      )
      .then((res) => {
        this.setState({ data: res.data });
      });
  };
   render()
      return(
            <SearchBar  
               placeholder="Search Food..."
               onChangeText={this.updateSearch}
               value={data}
             />
            <List style={{ paddingTop: hp("2%") }}>
              <TouchableOpacity>
                {this.state.data.map(({ type }) => (
              <Text>{this.state.type.products.title}</Text>
            ))}
              </TouchableOpacity>
            </List>

Hey everyone, I'm trying to get data from the Spoonacular database using axios, I'm trying to search the food with the SearchBar and display the content in the List, I'm new to programming and I'm not very sure of what I'm doing, when I run the code it tells me [Unhandled promise rejection: Error: Request failed with status code 400] and nothing shows on the list.

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

  • 1
    It's exactly as the error says. The request failed, and since you didn't add a `.catch`, the rejection is unhandled. You're probably not requesting the API properly. – CertainPerformance Mar 24 '21 at 15:01
  • Thanks, I added the `.catch`, but can't figure out what is wrong with the request for the API –  Mar 24 '21 at 15:07

1 Answers1

0

You are missing the query parameter. According to the docs it's required. So a correct request would be something like

let query = ...; //get hte value from the searchbar
axios
  .get(
    `https://api.spoonacular.com/food/products/search?query=${encodeURIComponent(query)}&apiKey=1234&number=100`
  )
  .then((res) => {
    this.setState({ data: res.data });
  })
  .catch(error => {
    console.log(error.response.data);
  });

The body of the erroneus response probably would include a hint ...

derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • You are right, the problem is that if I insert `query=pizza`, the only results that will show are pizzas, how can I change the query with the input from the `SearchBar` –  Mar 24 '21 at 15:27
  • I'm not using react or react-native, so I can't help you with how to get the value from the searchbar. But once you got it, you can simply add it to the query like shown above – derpirscher Mar 24 '21 at 15:33