Using the axios response to assign data object in VueJS

When making an API call, I am receiving an expected error. While I am able to log the error message in the console, I am encountering issues trying to set a vuejs data variable with the response. Can anyone point out what I might be doing incorrectly?

        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;
                });
            }
        }

While

console.log(error.response.data.error)
works as expected, the line
this.errors = error.response.data.error;
is not functioning properly. Any insights on how to resolve this issue?

Answer №1

When dealing with the 'catch' handler, the value of 'this' may not be what you expect. To address this issue, consider using an arrow function like

.catch(error => { this.errors = error.response.data.error; })
.

If your JavaScript environment does not support ES6 features, you can utilize Function.bind(this) as an alternative.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

Stopping an AngularJS timeout from running

I have a multi-platform app created using AngularJS and Onsen/Monaca UI. In my app, I have a feature that detects button clicks and after a certain number of clicks, the user is directed to a confirmation screen. However, if the user takes too long to mak ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

The error message "Next.js 14 does not recognize res.status as a function"

I'm a newcomer to Next.js and I've been wrestling with an issue all day. Here's my API for checking in MongoDB if a user exists: import {connect} from '../../../../lib/mongodb'; import User from '../../../models/userModel&ap ...

Programmatically select rows in multiple mode using Primevue Datatable

Currently, I am utilizing the PrimeVue Datatable which includes multiple selection checkboxes. One key feature that I aim to implement is the ability to add a new row to the table and have it automatically selected upon addition. However, I am encounterin ...

Using the JavaScript selectionchange event to target a specific element exclusively

I am looking for a way to incorporate a JavaScript selectionchange event on a specific div element. The goal is to display a highlighter box when the user selects text from the DOM. I was able to achieve this functionality for web using an onmouseup event, ...

The click event in jQuery is being blocked by the use of "display:none

Currently, I have implemented a search box feature with search suggestions: <input id="searchBar" /> <div id="searchSuggestion"></div> The searchSuggestion div is dynamically updated using jQuery ajax whenever an input is entered (imple ...

Massive Memory Drain Due to XMLHttp POST Request

Is there a way to prevent XHR POST Memory leak in my web app? I have searched extensively for solutions but have not found any satisfactory answers. My issue is similar to the one described in this blog post that outlines the problem without offering any f ...

Experiencing complications with an Angular 2 router

When a user logs into the system, they are greeted with a navigation bar featuring options like Dashboard, Customers, and Product. Below is an excerpt from my routes file: app.routing.ts export const router: Routes = [ { path: '', redir ...

Highlighting of Vue directives in HTML within WebStorm

Can the Vue attributes and directives be highlighted? Including those in quotes. ...

Is it necessary to match GET and POST routes only if a static file does not match?

I am encountering an issue with my routes and static definitions in Express. Here is my route setup: app.get('/:a/:b/:c', routes.get); Along with this static definition: app.use('/test', express.static(__dirname + '/test')); ...

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Extend GridView cell for file preview and download

Within my gridview, there is a column labeled "File Name" which includes the names of various files. I am looking for a way to click on a specific file name and be able to view its content as well as save or download the file. I am open to all suggestions ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...

Utilizing Vue.js 2.x to send a REST API request with a collection of objects

I currently have an array of objects stored in state, and my goal is to send this entire structure to a back end API for processing and receive a new set of values in return. Below is a simplified representation of this structure as viewed in the develope ...

Provide net.socket as a parameter

What is the best way to pass the net.socket class as an argument in this scenario? Here's my code snippet: this.server = net.createServer(this.onAccept.bind(this)); this.server.listen(this.port); } Server.prototype.onAccept = function () { // Ho ...

How to add multiple entries using Node.js and Tedious

I am currently working with an array of customer objects that I need to insert into a SQL database. These customer objects are retrieved from the request data. For this task, I am utilizing Tedious for handling the request and Tedious Connectionpool to ma ...

Protractor - Error: prop is undefined

Need assistance in identifying an error. Currently, I am learning Protractor and attempting to create a basic test using Page Object. //login_pageObject.js let loginContainer = function() { this.usernameInput = $("input.login-form-01"); this.passwordInp ...