What could be causing the error "Cannot read the state property of undefined in react-native?"

I really need some assistance. I am attempting to create a JSON object called users in my state properties to test the functionality of my authentication system. However, when I tried to access it, I encountered the error "Cannot read property 'state' of undefined" with the error pointing to this part of the code const { users, textInputEmail, textInputPassword } = this.state. Additionally, when I checked the users variable, it showed 'undefined'. What did I do incorrectly?

import React, { Component } from 'react'
import { View, TextInput } from 'react-native'
import { MyButton, ErrorMessage } from '../uikit'
import { FormStyle, InputStyle } from '../constants/styles'
import { SIGN_IN, SUCCESS } from '../routes'

export class LogIn extends Component {

    state = {
        users: {
            user: [
                {
                    name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="177d786773676c72725b66737279797b6275387a7674">[email protected]</a>',
                    password: '12345678'
                },

                {
                    name: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="466f6a60657a686f48787e61636275233a3634">[email protected]</a>',
                    password: '87654321'
                }

            ],
        },
        textInputEmail: '',
        textInputPassword: ''
    }

    isUser() {
        console.log(users)
        const { users, textInputEmail, textInputPassword } = this.state
        let currentUser, password;

        currentUser = users.map((user) => user.name == textInputEmail ? user : 'unknown')

        if (currentUser == 'unknown')
            return alert('Incorrect user or password!')
        else {
            if (currentUser.password == textInputPassword)
                this.props.navigation.navigate(SUCCESS)
        }
    }

    render() {
        const { mainContainer, buttons } = FormStyle
        const { container, text } = InputStyle

        return (
            <View>
                <View style={mainContainer}>
                    <View style={container}>
                        <TextInput
                            style={text}
                            placeholder={'Email/Login'}
                            onChangeText={(value) => this.setState({ textInputEmail: value })}
                        >
                        </TextInput>
                        <ErrorMessage errorText={'Incorrect email'} />
                    </View>

                    <View style={container}>
                        <TextInput
                            style={text}
                            placeholder={'Password'}
                            secureTextEntry={true}
                            onChangeText={(value) => this.setState({ textInputPassword: value })}
                        >
                        </TextInput>
                        <ErrorMessage errorText={'Incorrect password'} />
                    </View>

                    <View style={buttons}>
                        <MyButton
                            name={'Log in'.toUpperCase()}
                            onPress={this.isUser} />
                        <MyButton
                            name={'Sign in'.toUpperCase()}
                            onPress={() => this.props.navigation.navigate(SIGN_IN)} />
                    </View>
                </View>
            </View>
        )
    }
}

Answer №1

To ensure the correct 'this' value in React class components, it is necessary to bind the function. There are multiple ways to achieve this, which can be found here.

One approach is to update the declaration of your 'isUser' method from:

isUser() {
  ...
}

To:

isUser = () => {
  ...
}

Alternatively, you can bind it within a constructor like so:

export class LogIn extends Component {
  constructor(props) {
    super(props);
    this.isUser = this.useUser.bind(this);
  }
  ...
}

Another option is to bind the function directly in the 'render' method, as shown below:

<MyButton
  name={'Log in'.toUpperCase()}
  onPress={this.isUser.bind(this)} />

Answer №2

When you utilize the following code:

onPress={this.isUser}

You're disconnecting isUser from the component's scope, resulting in "this" becoming undefined when it is called. To resolve this issue, you can create an arrow function that simply invokes this.isUser():

onPress={() => this.isUser()}

Alternatively, you can turn isUser itself into an arrow function:

isUser = () => {
  ...
}

If you are interested in a more detailed explanation of why this change is necessary and how it impacts the code, I have discussed it further here.

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

Is it possible to analyze the performance of NodeJS applications using Visual Studio Code?

I have managed to establish a successful connection between the VS Code debugger and my remote NodeJS target through the Chrome protocol. I am aware that this protocol allows for profiling and performance measurements within the Chrome Dev Tools, but I am ...

Unable to modify the name of an element's class due to restrictions in JavaScript

I am trying to switch the class of an element from score -box1 to score -box1.-active. I defined a constant $target in order to access the class score -box1, however it is not functioning as expected. const $target = document.getElementByClassname('sc ...

Using d3 or ajax to read a local file containing tab-separated values may result in a syntax error appearing in the Firefox development console

The reading operation is functioning as expected. However, I encountered a syntax error in the Firefox console while going through multiple files, which can be quite tedious. These files are annotation files formatted like (time \t value) with no head ...

Is it possible in ReactJS to return JSX from a callback function?

After spending some time working with react, I encountered a basic issue that has me stumped. In the Login component, I am submitting a form and if it returns an error, I want to render a snackbar message. handleSubmit = (event) => { event.preven ...

Error encountered while attempting to convert a unique custom object to JSON in Jersey

Before jumping to conclusions and marking this question as a duplicate, I want to clarify that I have already explored the solutions provided in A message body writer for Java class not found javax.ws.rs.WebApplicationException: com.sun.jersey.api.Messag ...

Guide to using Angular $resource to pass query parameter array

My goal is to implement a feature that allows users to be searched based on multiple tags (an array of tags) using the specified structure: GET '/tags/users?tag[]=test&tag[]=sample' I have managed to make this work on my node server and hav ...

Disable the ability to close the dialog box by clicking

this is my dialog <div *ngIf="visible" class="overlay" (click)="close()"> <div role="dialog" class="overlay-content"> <div class="modal-dialog" (click)="$event.stopPropagation()"> <!-- Modal content--> ...

What could be causing React onclick events to not trigger when wrapped within a Vue application? (No additional libraries)

As I dive into the world of combining React and Vue components, I encountered an interesting challenge... const RootTemplate = () => { return ( <div id="vue-app"> ... <IconButton color="inherit" onClick={thi ...

How can I search across different fields within a single collection using meteor-autocomplete?

I have implemented mizzao/meteor-autcomplete to retrieve matching items from a MongoDB collection based on user input. While I can successfully search for items in one field, I am facing difficulty searching multiple fields within the same collection. My ...

Tips for verifying the input field with specific requirements in Angular 6

There is an input field that needs to validate text based on certain logic conditions: No spaces should be allowed in the formula. The operators (and,or) must be lowercase and enclosed in curly brackets {}. The number of opening '(&apos ...

Is there a way to customize the CSS for a single blog post and add a 5-star rating system without affecting other posts?

After launching my blog on Google's Blogger, I wanted to add a unique touch by incorporating a static 5-star rating system in my Books I Read Section. I thought about using CSS to customize each book post and display anywhere from 1 to 5 stars for vis ...

When attempting to convert Unicode to a Python dictionary, an unexpected error occurs

I built an Android app that sends SMS messages from the mobile app as displayed below: my_dict = {\ u'1': u'"sender" : "dz-080008", "text" : "enjoy 10%<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d4d6c4 ...

Enhancing an array of objects by incorporating properties using map and promises

I am encountering an issue with assigning a new property to each object in an array, which is obtained through an async function within a map method. Here is the code snippet that I am using: asyncFunction.then(array => { var promises = array.map(o ...

Internet Explorer's support for the `<summary>` tag in HTML

Is there a method to enable the summary tag in Internet Explorer 11, such as using an external library? <details> <summary>Here is the summary.</summary> <p>Lorem ipsum dolor sit amet</p> </details> App ...

How can you use mouseover events to display a popover and manipulate the div id?

In my scenario, I have multiple div elements and I want to display separate popover for each div. Initially, the popover is not shown on the first mouseover event but works perfectly on subsequent attempts. Below is the code snippet: $(document).read ...

Why isn't the click event triggering MVC 5 client-side validation for ajax posts?

To incorporate client-side validation with a click event for ajax posts, I followed a guide found at the following URL: Call MVC 3 Client Side Validation Manually for ajax posts My attempt to implement this involved using the code snippet below: $(&apos ...

Having trouble initializing a React Native project using npm/expo start?

After consulting the react-native documentation to create an android app, I followed these steps: npm install -g expo-cli After running the above command in my project file, I used the following commands: expo init first-proj cd first-proj Everything se ...

Obtain the printed value of a button via PHP and manipulate it using JavaScript

I have a dynamic table that displays results from a database. <table id="table" class="table datatable-responsive"> <thead> <tr class="bg-teal"> <th>#</th> <th>Date & Time</th& ...

React validation functionalities

Incorporating React, I am attempting to implement a validation feature within a footer containing multiple buttons with unique values such as home, orders, payments and more. My goal is to dynamically display an active state for the button corresponding to ...

What's the best way to integrate Bootstrap into my HTML document?

Hey there, I'm new to the coding world and just started learning. I could use some assistance with including Bootstrap v5.1 in my HTML code. The online course I'm taking is using an older version of Bootstrap, so I'm having trouble finding t ...