Error: Attempting to access property 'email' from an undefined object was unsuccessful

I'm currently working on a Vue.js app with Laravel but I'm having trouble accessing the component from the object. What steps should I take?

<script>
import axios from 'axios';
export default {
    data : function (){
        return {
            email: '',
            password: '',
            remember: 'true',
            errors: [],
        }
    },
    methods : {
        validateemail(mail){
            var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(mail);
        },
        attemptlogin(){
            this.errorsarray = [];
            axios.post('/login', {
                email: this.email,
                password: this.password,
                remember : this.remember
            }).then(function (response) {
                    location.reload();
                }).catch(function (error) {
                var code = error.response.status;
                console.log(this.email);
                    if(code == 422){


                        this.errors.push("Incorrect information");

                    }else{
                        console.log('no');
                        this.errors.push('Internal server error please try again later')
                    }
                }).then(function () {
                console.log('here');
            });
        },
    },
    computed : {
        isValidInput() {

            return this.validateemail(this.email) && this.password;
        }
    }
}

Additionally, I keep encountering the following error:

Uncaught (in promise) TypeError: Cannot read property 'email' of undefined

I'm uncertain of the reason behind this error. Any assistance would be greatly appreciated. Thank you in advance.

Answer №1

Opt for the () => {} function syntax over function() {}. The former ensures proper binding of this.

.catch(error => {
    console.log(this.email);
})

If you insist on using function() {}, remember to explicitly bind this:

.catch(function (error) {
    console.log(this.email);
}.bind(this))

Refer to this answer for a detailed explanation on bind.

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

Understanding the concept of event bubbling through the use of querySelector

I am currently working on implementing an event listener that filters out specific clicks within a container. For instance, in the code snippet below I am filtering out clicks on elements with the class UL.head. <div> <ul class="head"> < ...

NPM rimraf - proceed with the execution even if directories are not found (do not halt with exit code 1)

My npm script is set up to run a series of synchronous commands, starting with npm run clean:install". Here is the sequence: "install:all": "npm install && bower install", "clean": "npm run rimraf -- node_modules doc typings coverage wwwroot bow ...

Is there a way to retrieve values from TextFields and Select elements by simply clicking on a button?

I am currently working on a project using react, redux, and material ui. I need to retrieve data from a TextField in order to make an order. The code snippet below showcases my current implementation: <Select value={product.color_set[0].title}> { ...

Is your website's Google analytics event tracking not giving you the feedback you need

Here's what I'm trying to achieve in the code below: Set up Google Analytics on the page Add a jQuery click event based on specific query strings and domain characters Trigger a Google Analytics tracking event with the click event Implement cod ...

Angular 12 app does not have Express server searching for static files

Context I am in the process of transferring an Angular application to a GKE cluster. Unfortunately, due to company policy, the base docker image I am required to use does not support the installation of new software such as shell or Angular CLI commands l ...

Sending a parameter to the window.onload callback function

Is there a way to pass parameters from ModelAndView to a window.onload function in JavaScript within an HTML file? Here is an example of how it can be done: @RequestMapping(value = "/admin/printtext") public ModelAndView printtext() { ModelAndView mo ...

Generating conference itinerary - establishing agenda function (Sequelize)

const _ = require('lodash'); const Promise = require('bluebird'); const Sequelize = require('sequelize'); const ResourceNotFound = require('./errors').ResourceNotFound; const ResourceAccessDenied = require('./er ...

Utilize $.ajax to gracefully wait for completion without causing the UI to freeze

Consider a scenario where there is a JavaScript function that returns a boolean value: function UpdateUserInSession(target, user) { var data = { "jsonUser": JSON.stringify(user) }; $.ajax({ type: "POST", url: target, data: ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...

Replacing a select tag based on a change in its sibling element is a common task in

I am dealing with three select tags that are displayed in a cascading manner within a div. These select tags have identical HTML structure, with the only difference being the options they contain. They all share the same name and id attributes. <div cl ...

Reorganize the placement of table columns between different rows

I am currently using a software program that automatically generates a form based on the selected options. The code for this form is generated in tables, which I am unable to directly edit. However, I would like to have the Amount, radio buttons, and their ...

Sinon threw an assertion error out of the blue

Just diving into using Sinon and facing a small hiccup. Let's say we have a module (named myModule.js) defined as follows: //myModule.js var _f2 = function() { console.log('_f2 enter'); return {prop1:'var1'}; }; var f1 = ...

Displaying a div on click using Jquery will only impact one div at a time

I am encountering an issue with my WordPress setup. Within my loop, I have a clickable link that toggles a div to show or hide content. However, since each item in the loop uses the same class, clicking on one link activates all of them simultaneously. &l ...

Is it possible to generate AMP pages using React server-side?

After experimenting with rendering the AMP page by generating HTML on the server using React, I have successfully created a component that fetches data from the API and renders the necessary amp tags. The component is responsible for producing a plain HT ...

Vuex - The action type CreateProfile or ProfileList is not recognized

Hello everyone! I am working on a project where I need to create models and maintain a list of them. Currently, I have integrated two separate projects successfully: https://github.com/apirobot/django-vue-simplenote and https://github.com/jakemcdermott/ ...

The use of $scope.$destroy may resolve memory leak issues, but it can also cause

In my TypeScript AngularJS application, I have a child directive that is dynamically generated. The template and controller are assigned at runtime based on the requirements of the situation, with multiple directives within the template. To display multipl ...

What causes the DOM to be updated upon each opening of the browser extension for Chrome?

Here is the default position: https://i.stack.imgur.com/tkWCA.png After checking it: https://i.stack.imgur.com/tdzbg.png When I click anywhere on the page to hide the dom extension output (without showing popup.html); However, when I reopen the extens ...

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...

AngularJS supports asynchronous validation on blur

Using Angular JS version 1.5.6, I am looking to implement asynchronous input validation that occurs only on blur. However, I am unable to use modelOption: {debounce: 500} or modelOption: {updateOn: 'blur'} due to the directive being used with oth ...

Can anyone suggest a reliable method for comparing two dependencies trees generated by the `npm list` command?

Prior to launching the project, it is crucial to analyze the updated dependencies that could potentially affect other pages. Utilizing the npm list command can help generate a comprehensive tree of all dependencies. What is the most efficient way to comp ...