Search code examples
vue.jsaxiosvuex

Axios / Json for loop, How can I prevent this error?


part of my code goes like this, URL is under for-loop.

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

I'm getting this error because the response doesn't contain a products property

I want to push the getJsonAPI only if there's a something inside the "data" tree. The code works as intended but there's an error and my OCD won't allow me to continue with the project :( Any ideas? I'm new to this stuff

enter image description here

enter image description here

enter image description here


Solution

  • 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 :)