[Vuejs]-Axios / Json for loop, How can I prevent this error?

1👍

It happens because undefined.length is throws error.

if (response && response.data && response.data.data && 
    response.data.data.products && response.data.data.products.length) {
    state.jsonGetProductsAPI.push(getJsonAPI);
  }

This code is not gonna throw error 🙂

2👍

You could just use optional chaining (?.) syntax. It was designed specifically for cases like yours, so you could replace a && a.b && a.b.c with a?.b?.c:

axios.get(Url).then((response) => {
  const products = response.data.data.products;
  if (products?.length) {
    state.jsonGetProductsAPI.push(products);
  }
});

If there are cases where the response doesn’t contain a data property, you should chain it optionally as well:

const products = response.data.data?.products;

Also note you don’t need any polyfills, Vue will transpile it for you (into a && a.b && a.b.c syntax).

👤tao

0👍

You should check that data is present.
It is easier if you do all data checks at the top of the method and bailout (return or anything else that’s acceptable) there.

axios.get(Url).then((response) => {
   if (!response.data || !response.data.data || !response.data.data.products) {
    return
   }

   // now you are sure that response.data.data.products is truthy

   let getJsonAPI = response.data.data.products;
   if (response.data.data.products.length > 0) {
     state.jsonGetProductsAPI.push(getJsonAPI);
   }
});

PS: errors should not be tolerated, it shouldn’t be a matter of OCD.

Leave a comment