user12325934
user12325934

Reputation:

How to fix Uncaught (in promise) TypeError: Cannot set property of undefined

I get an error when I want to send the value from the API results to the data, the error is like this

Uncaught (in promise) TypeError: Cannot set property 'notification' of undefined at eval (HeaderPortal.vue?070f:367)

this my HeaderPortal.vue

data() {
  return {
    notification: []
  }
}

mounted: {
  const res = this.GET('/api/v2/notification', 'BEARER', null).then(function(res) {
     console.log(JSON.parse(res))
     this.notification = JSON.parse(res);
  });
}

this.GET comes from here

methods: {
  async GET(url, headers, callback) {
    const options = headers === 'BASIC' ? HEADERS_BASIC : HEADERS_BEARER;
    try {
      const response = await axios.get(`${BASE_URL}${url}`, options);
      return (JSON.stringify(response));
    } catch (e) {
      console.error(e);
    }
  }
}

how to handle it? is there something wrong in my code?

Upvotes: 2

Views: 21235

Answers (3)

salvo720
salvo720

Reputation: 511

answer up is low clear , let me show what do with example :

data() {
      return {
        notification: []
      }
    }
    methods: {
        const res = this.GET('/api/v2/notification', 'BEARER', null).then( res =>  {
          console.log(JSON.parse(res))
          this.notification = JSON.parse(res);
        });
    }

i hope be useful

Upvotes: 2

Siddharth Chauhan
Siddharth Chauhan

Reputation: 1

this in the inner function refers to the function only, therefore it is not working. Instead, write:

s=this;
const res = this.GET('/api/v2/notification', 'BEARER', null).then( 
function(res) {
      console.log(JSON.parse(res))
      s.notification = JSON.parse(res);
    });
}

Upvotes: -1

Florian Pallas
Florian Pallas

Reputation: 582

If you need to access the this keyword, make sure you use arrow functions () => {} instead of regular functions function() {} in your callback. If you don't, the this keyword will be undefined in your case. This is why you get an error trying to set this.notification = JSON.parse(res); in your first code snippet.

Your first code snippet is a bit weird, maybe you forgot to copy something? You code should not be directly inside the methods object. It should be in the mounted hook, or in a proper method like in the second snippet.

Upvotes: 11

Related Questions