Home > Software engineering >  How to check if Axios response data is empty
How to check if Axios response data is empty

Time:10-28

How to check if axios response is empty. Some times my response.data will be [ ]. Currently it aways alert "data there" is there a better way to do this than response.data.lenght >= 1

return await axios
    .get(url.rest_api   '/team_members', {
      params: {
        primaryOwner: firebase.auth().currentUser.uid,
        teamMemberEmail: emailText,
      },
    })
    .then(response => {
      if (response.data) {
        alert('data there');
      } else {
        alert('nothing here');
      }
      return response.data;
    })

CodePudding user response:

you can check the availability with: const isDataAvailable = response.data && response.data.length;

CodePudding user response:

Check if the variable is set and if so is the array length greater than 0

if (response.data && response.data.length)

With TypeScript

if (response.data?.length) 

CodePudding user response:

According to the Response Schema, response.data is an instance of an Object (please correct me if I'm wrong). So we can check if data is not an empty string AND if it's constructor is and instance of an Object.

That's how I check it

if (response.data !== '' && response.data.constructor === Object) {
   //do something
}

Never fails (for me at least)

  • Related