0

I'm making an API call and getting (an expected) error back. I can console log the error message but I can not seem to set a vuejs data variable with the response. What am I doing wrong?

        data: {
            ...
            ...
            errors: null
        },
        methods: {
            checkConnections: function (event) {
                axios.post('/checkconnections', {
                    //form data is passed here
                    ...
                    ...
                })
                .then(function (response) {
                    console.log(response);
                }).catch(function (error) {
                    console.log(error.response.data.error);
                    this.errors = error.response.data.error;
                });
            }
        }

The console.log(error.response.data.error) part works fine but the assignment this.errors = error.response.data.error; is not. Any ideas?

twigg
  • 3,753
  • 13
  • 54
  • 96
  • 1
    https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback - You could also read this post for additional clarity. – John Jun 11 '18 at 13:53

1 Answers1

3

The this value inside your catch handler isn't what you are expecting. The easiest way to fix that problem is to use an arrow function like .catch(error => { this.errors = error.response.data.error; }).

If your environment won't allow ES6 features, you can use Function.bind(this) instead.

BCDeWitt
  • 4,540
  • 2
  • 21
  • 34