最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to deal with empty response in axios? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Aug 28, 2017 at 18:59 Karlom asked Aug 28, 2017 at 17:21 KarlomKarlom 14.9k29 gold badges78 silver badges118 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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);
            });
    }
}

You could throw a custom error that will be catch by the catch method.

 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?
   if (!response.data || response.data.length == 0) {
     const emptyDataError = new Error('Invalid data');
     emptyDataError.statusCode = 500;
     throw emptyDataError;
   }
   this.jokes = response.data;
 }).catch(function (error) {
   console.log(error);
 });
发布评论

评论列表(0)

  1. 暂无评论