What is the best way to handle receiving no response in axios?

Using axios in conjunction with vue.js allows me to implement unlimited pagination for fetching data. Everything seems to be working well, except for one scenario: when there is no data available to render.

 fetchData() {
     this.loading = true
     this.page++;
     axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( 
     response => 
     //what should I do if the response has no data?
      this.jokes = response.data).catch(function (error) {
        console.log(error);
      });

I'm trying to figure out how to prevent rendering when we have reached the last page and there are no more data elements to display.

Despite checking the documentation, I have not been able to find a solution to my query.

Answer №1

Perhaps implementing some basic flag logics could be beneficial. While I have made assumptions, you are always free to define your own logic

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

Answer №2

To handle the case when there is no data in the response, you can throw a custom error that will be caught by the catch method.

 fetchData() {
 this.loading = true
 this.page++;
 axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( 
 response => {
   // Check 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);
 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The menu options pulled from a JSON file generated on the server using Nextjs are not showing up in the HTML source code

Apologies if the title is a bit unclear. Let me try to explain: my website is built using Next.js and retrieves data from Sanity Studio (CMS). In Sanity, users can create menu items which are displayed in the footer component, sidebar component, and header ...

Automatically generated error notifications for Express-Validator

I am looking to implement an Express API and incorporate request input validation using express-validator. Here is my current validation middleware: protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> ...

Query the mongodb collection by utilizing the less than and greater than operators to filter data based on the date field

const queryMatch = {departureDate: {$gte: new Date(query.departureDateMin),$lte: new Date(query.departureDateMax)}}; const flightsByCriteria = await this.flightModel.find(queryMatch).exec(); The query above is not returning any results. Interestingly, I a ...

Hosting services for forms and JSON data

I have recently completed the development of my website using HTML, CSS3, jQuery, and JavaScript. Like many others, it includes a form for clients to submit their projects via email. After some research, I came across suggestions to use NodeJS for server-s ...

The button effortlessly transforms into a sleek email submission form

I have a button that is already styled with basic CSS properties for active and hover states. I would like to add functionality so that when the "Join the Loop" button is clicked, it transforms into a simple email form similar to the one found at Apologie ...

Is there a more secure alternative to using the risky eval() function? Do I need to take the lengthier route by implementing a switch case instead?

I've been practicing and honing my Javascript skills by working on a calculator code that initially had lots of repetitive lines. I managed to simplify it, but I am aware that using the eval() method is not generally recommended. let current = 0; f ...

Attempting to retrieve currentScript is causing a typeError to be thrown

I'm attempting to access a custom attribute that I added to my script tag: <script type="text/javascript" src="https://.../mysource.js" customdata="some_value"></script> To make this work on Internet Explorer ...

Creating curved edges in Three.js using Javascript

One of my functions involves creating a track using 3D points from a separate file called trackline.json. The example data in the file looks something like this: [{"x":5.01088018657063,"y":0.033095929202426655,"z":-1.469083126 ...

Emulating a button press on the login screen

I have been attempting to utilize jQuery to simulate a button click on a login page. Interestingly, the conventional JavaScript method functions as expected: document.getElementById('loginButton').click(); However, the same action using jQuery ...

Unable to reach the URL of a dockerized application in a selenium dockerized image

I have successfully dockerized a vue.js app running on localhost:8090 on a VM server. By connecting the VM server to my VS Code using SSH, I was able to access the vue.js app on my local machine's Chrome browser after setting up port forwarding. Howev ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

Saving an HTML5 canvas image to an MSSQL varbinary(max) field: A step-by-step guide

SAVING CANVAS IMAGE AS BASE64 STRING TO HIDDEN FIELD This script binds the base64 string to a hidden field on click event. save.addEventListener('click', function (event) { var dataUrl = canvas.toDataURL(); $('txtbx').val(dataUrl) ...

Is it possible to utilize Nuxt exclusively as a Single Page Application (SPA)?

My current tech stack includes Angular and Node.js. I have dabbled with Vue on a few simple projects, and recently came across Nuxt3 in some videos. I'm curious to know if Nuxt3 supports single page applications (SPAs) with a Node.js API integration. ...

Obtaining a state hook value within an imported function in React

In order to access a value from the state hook stored in a special function, it is straightforward to do so in a functional component. For example, this can be achieved in App.js like this: import React from 'react'; import { Switch, Route, with ...

Customizing the Mui Theme in a Unique Way

After generating an MUI component from Mui DatePicker, I encountered the following code: <span class="my-theme-MuiTypography-root my-theme-MuiTypography-caption my-theme-MuiDayCalendar-weekdayLabel css-1mln09i-MuiTypography-root-MuiDayCalendar-week ...

Ways to update div using jquery without creating copies

I have a code snippet that refreshes a div every 10 seconds: <script type="text/javascript> setInterval(function(){ $('#feed').load('forum.php #feed').fadeIn("slow"); }, 10000); </script> It works well, but there is one is ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

Node.JS encountered an issue preventing the variable from being saved

I've been attempting to store the request.headers, but every time it outputs as [object Object] in the txt file. var http = require("http"); url = require("url"); fs = require("fs"); var events = require('events'); var even = new events.Ev ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...