Having trouble accessing the `controls` property of an undefined variable in a function() implementation

I'm struggling to understand why my authHandler function is returning the error "cannot read property 'controls' of undefined" even though I have defined it. At least, I believe I have - see below.

Any fresh perspectives on this issue would be greatly appreciated!

class SignUp extends Component {
    state = {
        controls: {
            email: {
                value: "",
                valid: false,
                validationRules: {
                    isEmail: true
                },
                touched: false
            },
            password: {
                value: "",
                valid: false,
                validationRules: {
                    minLength: 6
                },
                touched: false
            }
        }
};

authHandler = () => {
    return new Promise (function(resolve, reject) {
        const authData = {
            email: this.state.controls.email.value,
            password: this.state.controls.password.value
        };
        this.props.onTryAuth(authData, this.state.authMode);
    })
    .then(() => {
        this.props.onAddUserData(
            this.state.controls.userName.value,
        )
    })
    .catch(err => {
        console.log(err);
        alert("Oops! Something went wrong, please try again")
    })
};

Answer №1

It is possible that you are losing the reference to the current scope, which can be verified by using console.log(this). Below is an updated code snippet that should resolve this issue. Converting the function to a lambda expression will prevent the reset of the this. Additionally, in the code you provided, there were two missing closing }.

class SignUp extends Component {
    state = {
        controls: {
            email: {
                value: "",
                valid: false,
                validationRules: {
                   isEmail: true
                },
                touched: false
            },
            password: {
                value: "",
                valid: false,
                validationRules: {
                    minLength: 6
                },
                touched: false
            }
       }
    }
};    

authHandler = () => {
    return new Promise ((resolve, reject) => {
        const authData = {
            email: this.state.controls.email.value,
            password: this.state.controls.password.value
        };
        this.props.onTryAuth(authData, this.state.authMode);
    })
    .then(() => {
        this.props.onAddUserData(
          this.state.controls.userName.value,
       )
    })
    .catch(err => {
        console.log(err);
        alert("Oops! Something went wrong, please try again")
    })
};

Alternatively, you can also approach it like this:

authHandler = () => {
    // Save a reference to 'this' for use within this function
    var self = this;
    return new Promise (function (resolve, reject) {
        // Since a function is declared above, 'this' is reset to the function's scope
        // and not the one entering authHandler.
        const authData = {
            email: self.state.controls.email.value,
            password: self.state.controls.password.value
        };
        self.props.onTryAuth(authData, self.state.authMode);
    })
    .then(() => {
        self.props.onAddUserData(
          self.state.controls.userName.value,
       )
    })
    .catch(err => {
        console.log(err);
        alert("Oops! Something went wrong, please try again")
    })
};

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

Using Three.js to render images on several canvases with WebGLRenderer from various perspectives

I have encountered a challenge where I need to use only 1 WebGLRenderer, but have multiple camera views that should be displayed on unique canvases. In the current setup, I have 9 views placed in one canvas, each with distinct cameras, scenes, and meshes w ...

Obtain a file (attachment) by utilizing an href link that includes an Authorization Header

When using my web API app (.NET WebAPI), I need to include the authorization header when a download link is clicked. Unfortunately, simply using an href link does not pass the authorization header, resulting in the API denying the download request (using A ...

Vue.js is prevented by Content-Security-Policy

Running a HTML page on my node.js server with express.public() function. I included the following in my html page: <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> However, Chrome gave me a Content-Security-Pol ...

Tips for sorting through a multi-dimensional array of objects

I'm looking to filter this array based on the attributevalue. For example, if I search for blue color, I want all shirts in blue color to be displayed. And then if I further search for cotton fabric in blue color, I want all cotton products with blue ...

What is the best approach to transform a lengthy collection of 'watch' statements into a functioning solution using VueJS?

I am new to vueJS and need some help with optimizing my code. I have a long list of watch functions that are all essentially the same, but I'm not sure how to convert them into a more efficient and functional approach. These watch functions are all r ...

Regular expressions can be used to extract all attributes from a webpage that begin with a specified value

I have a simple question - how can I retrieve the values of all attributes that start with http://example.com/api/v3?? For instance, if a webpage includes: <iframe src="http://example.com/api/v3?download=example%2Forg"> <meta twitter="http://exam ...

Integrating DHTMLX Scheduler with Node JS for seamless scheduling solutions

Having diligently followed the DTHMLX Scheduler guide, I've encountered an issue with the db.event.insert() function not working, as the associated route fails to trigger. Interestingly, data from my MongoDB displays correctly when inserted via the sh ...

Access an attribute using slashes in Jquery

I've been struggling to use jQuery to select an object based on a unique filename attribute. However, I'm facing issues with escaping slashes when the selector is created using a variable. Despite spending hours trying different combinations, I s ...

Access denied: Unable to rename directory '/usr/local/lib/node_modules/expo-cli' due to permission restrictions

After encountering an error that appeared to be related to permissions, I spent some time troubleshooting and finally found a solution. I wanted to share it here in case it can help others facing the same issue. If anyone has alternative solutions, please ...

Dealing with a Promise and converting it into an array: a step-by-step

I am encountering difficulties progressing with my Promise returned from the getPostedPlaces() function. After executing getAll(), an Array is displayed as shown below. Although the array appears to be correct, I am unsure how to make the getAll() function ...

Node.js Mongoose MongoDB causing issues with bodyparser

Combining two different applications - an authentication app and a to-do app where users input data and the app displays it. Both apps work fine separately, but after merging them, there is a parse error in the second app. The issue seems to be related to ...

Unravel the base64 encoded message from JavaScript and process it in Python

I'm currently facing an issue in Python while trying to decode a string sent by jQuery. Although I am not encountering any errors, I receive an encoding error when attempting to open the file. My objective is to decode the string in order to save it ...

Display a complex JSON string in an ng-grid

My web service is designed to generate a JSON string using the following code: JavaScriptSerializer j = new JavaScriptSerializer(); return "[" + string.Join(",", v.getProbingJobs().Select(a => j.Serialize(a)).ToArray()) + "]"; (The getProbingJobs func ...

"Troubleshooting a problem with Mongoose's findOne.populate method

There is an array of user IDs stored in the currentUser.follow property. Each user has posts with a referenceId from the PostSchema. I am trying to populate each user's posts and store them in an array called userArray. However, due to a scope issue, ...

Creating a versatile Nuxt build that can be used across multiple environments

In the development of my Nuxt application, I am faced with the task of setting up two distinct environments - staging and production. Besides these, the local environment is also considered as staging. As part of this setup, I need to create specific comma ...

How can I utilize match props in React JS with the Context API?

Currently working on a basic application that utilizes context API, fetch, and react hooks for all components except the context API component due to ongoing learning of hooks. The challenge lies in incorporating the match prop within the context API prov ...

Using JQuery to switch classes and activate events

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <span class="fake_h">Too</span> </body> <script> $('.fake_h').click(function() { $(this).addClass( ...

Unable to integrate Express.js into my React JS project

Having trouble integrating express.js into my react js Project. After adding the following lines to my app.js code: const express = require('express') const app = express(); I encounter the error messages below: - Module not found: Error: Can&ap ...

Issue identified: Unforeseen SyntaxError encountered - token / was unexpected

Currently, I am working on a small application that is designed to showcase JSON data in a listview. In order to fetch the data, I have implemented a basic request feature. However, I am consistently encountering the following issue: Uncaught SyntaxEr ...

Adaptable Semantic UI form design

Welcome, internet friends! If anyone out there has a moment to spare and is familiar with Semantic UI, I could really use some assistance... Currently, I am working on a form that looks great on larger screens like this: https://i.stack.imgur.com/cafc5.j ...