Showing warning when API returns empty data (Vue.js / Axios)

Viewed 800

I am quite new with Vue.js and Axios. I was working on getting and displaying data from the API by search function, and trying to figure out how to display a warning/alert or something that would let the user know API response is empty.

Observed result: App shows the data when there's a match in the search box but does not show anything when there's no exact match

Expected result: When there's no exact match showing a text or alert on the front end to indicate "there is no match"

      
      axios.get(`API LINK HERE`,

    {
headers: {
      "x-rapidapi-host":"API HOST LINK HERE",
    "x-rapidapi-key":"API KEY HERE",
    "useQueryString":true
    },"params":{
    "format":"json",
    "date-format":"YYYY-MM-DD",
    "name":`${query}`

}
    })
    
      .then(response => this.itemData = response.data)
        
    }```
2 Answers

Just check any results using a conditional statement.

.then(response => {if (response.data=="") {// code here to alert user of empty response }})

You can set this.itemData to a message signalling an empty response or use some other method of alerting the user.

I'm not that familiar with Vue.js but I think this is more about javascript and you could do:

    axios.get(`API LINK HERE`, { headers: HEADERS})
      .then(res => {
          if (isEmpty(res.data) {
              alert("is empty");
          } else {
              this.itemData = response.data;
          }
      })
      .catch(error => alert("problem. try later")) // your error handling

if you like more try and catch:

try {
    const res = await axios.get(`API LINK HERE`, { headers: HEADERS});
    const itemData = res.data;
    if (isEmpty(itemData) {
        alert("is empty");
    } else {
        this.itemData = itemData;
    }
} catch (error) {
    alert("my error handling");
}
Related