How to deal with empty response in axios?

10,725

Maybe introducing some basic flag logics. I have taken the freedom to assume, but you can always define your logic

fetchData() {
    this.loading = true;
    if (this.page > 0) {
        axios.get(this.BASE_URL + '/api/jokes/page=' + this.page)
            .then(response => {
                const isDataAvailable = response.data && response.data.length;
                this.jokes = isDataAvailable ? response.data : [];
                this.page = isDataAvailable ? (this.page + 1) : 0;
            })
            .catch(function(error) {
                console.error(error);
            });
    }
}
Share:
10,725

Related videos on Youtube

Karlom
Author by

Karlom

Updated on June 04, 2022

Comments

  • Karlom
    Karlom almost 2 years

    I use axios with vue.js to fetch data as unlimited pagination. It works fine expect when there is no data to render:

     fetchData() {
         this.loading = true
         this.page++;
         axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( 
         response => 
         //how to exist  if there is no data in the response?
          this.jokes = response.data).catch(function (error) {
            console.log(error);
          });
    

    I'm wondering how to stop rendering when we reached to the last page and there is no more data to display?

    I've looked at the docs but could not find my answer.

  • Karlom
    Karlom over 6 years
    This does not work. I don't want to rewrite the whole function. Please limit your answer to breaking the function when response.data is empty.