Mohd Ali
Mohd Ali

Reputation: 145

TypeError: Cannot read property 'push' of undefined [VueJs]

I am trying to add an object to an array but it is not working with me, the program can't read the property push

I defined an array in <script>:

Data: function() {
  return {
     Projects: [
        {
           name: '',
           id: 0,
           subscribers: 0,
           products: {name:'',color:''},
        }
     ],
}

And in the function:

GetAllWorkspaces: function(){

   var app = this;

  const instance = axios.create({
       timeout: 1000,
       headers: {
              ........
            }
          });
  instance.get("XXXXXXX")
  .then( function(response) {
  console.log(response);
  Object.keys(response.data.result).forEach( function (product) {

      var subscribersCounter = 0;

      let example = {
         name: response.data.result[product].name,
         id: response.data.result[product].id,
         subscribers: response.data.result[product].subscribers,
         products: response.data.result[product].products,
      };

      let uploadedExample = {
         name: '',
         id: '',
         subscribers: '',
         products: {name:'',color:''},
      };

      uploadedExample.name = example.name;
      uploadedExample.id = example.id;

      if ( example.subscribers ) {
      Object.keys(example.subscribers).forEach(function (key) {
          subscribersCounter++;
      });
      }

      uploadedExample.subscribers = subscribersCounter;

      if ( example.products ) {
         Object.keys(example.products).forEach(function (Pkeys) {
            uploadedExample.products.name = Pkeys;
            Object.keys(example.products[Pkeys]).forEach(function (key) {
                if (key == 'color') {
                        uploadedExample.products.color = example.products[Pkeys][key];
                }
             });
          });
        }

        //add the new workspace to the list of workspaces.
        app.Projects.push(uploadedExample);

    });

    })
    .catch(function(error) {
        console.log(error);
     });

My problem is with this line

app.Projects.push(uploadedExample);

where when I try to push an object into the array, the error message is shown:

TypeError: Cannot read property 'push' of undefined

Upvotes: 0

Views: 9288

Answers (1)

M&#225;t&#233; Wiszt
M&#225;t&#233; Wiszt

Reputation: 410

As the error says, the problem is that app.Projects is undefined. This happens because 'this' refers to the function scope inside GetAllWorkspaces and not to the component scope (you can try it by console.logging 'this' - anyway- it is a good practice under all circumstances because 'this' can change from context to context). If you want to keep the component scope inside the method, you should use an arrow function like this:

GetAllWorkspaces: () => {
// do all your stuff
}

Upvotes: 1

Related Questions