React Native Component Error: Cannot read property '_this' of undefined

I am currently developing a face recognition application using React Native 0.63. I'm running my project using react-native run-android. However, I encountered an issue with Component Exception where it shows 'undefined is not an object (evaluating '_this'). Since I am new to React Native, I find it challenging to understand the meaning of this error. I have been following a tutorial for this project, but unfortunately, the tutorial is outdated. Therefore, I am struggling to update the code to the latest version of React Native. You can find the link to the tutorial here: Face Recognition using React Native. Kindly review the tutorial and help me resolve this issue.

import React from 'react';

import {StyleSheet,Text,View,Image} from 'react-native';
 
import NativeModules, { ImagePickerManager } from 'react-native';
 
import Button from './Button';
 
import RNFetchBlob from 'react-native-fetch-blob';
 
import _ from 'lodash';
 
const Detector = props => {

this.state = {
    photo_style: {
        position: 'relative',
        width: 480,
        height: 480
    },
    has_photo: false,
    photo: null,
    face_data: null
};

return (
  <View style={styles.container}>
     
    <Image
        style={this.state.photo_style}
        source={this.state.photo}
        resizeMode={'contain'}
    >
        { this._renderFaceBoxes.call(this) }
    </Image>
 
    <Button
        title={'Pick Photo'}
        onPress={()=>{this._pickImage.bind(this)}}
        button_styles={styles.button}
        button_text_styles={styles.button_text} />

    { this._renderDetectFacesButton.call(this) }

  </View>
);


}

  const _pickImage = () => {
 
this.setState({
    face_data: null
});

ImagePickerManager.showImagePicker(this.props.imagePickerOptions, (response) => {
     
  if(response.error){
    alert('Error getting the image. Please try again.');
  }else{
     
    let source = {uri: response.uri};

    this.setState({
      photo_style: {
        position: 'relative',
        width: response.width,
        height: response.height
      },
      has_photo: true,
      photo: source,
      photo_data: response.data
    });
     
  }
});



}
 
  const _renderDetectFacesButton = () => {
    if(this.state.has_photo){
        return  (
            <Button
                title={'Detect Faces'}
                onPress={()=>{this._detectFaces.bind(this)}}
                button_styles={styles.button}
                button_text_styles={styles.button_text} />
        );
    }
  }
 
  const _detectFaces = () => {
RNFetchBlob.fetch('POST', 'https://api.projectoxford.ai/face/v1.0/detect?returnFaceId=true&returnFaceAttributes=age,gender', {
    'Accept': 'application/json',
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': this.props.apiKey
}, this.state.photo_data)
.then((res) => {
    return res.json();      
})
.then((json) => {
     
    if(json.length){
        this.setState({
            face_data: json
        });
    }else{
        alert("Sorry, I can't see any faces in there.");
    }
     
    return json;
})
.catch (function (error) {
    console.log(error);
    alert('Sorry, the request failed. Please try again.' + JSON.stringify(error));
});
 



}
 
  const _renderFaceBoxes = () => {
if(this.state.face_data){

    let views = _.map(this.state.face_data, (x) => {
         
        let box = {
            position: 'absolute',
            top: x.faceRectangle.top,
            left: x.faceRectangle.left
        };

        let style = { 
            width: x.faceRectangle.width,
            height: x.faceRectangle.height,
            borderWidth: 2,
            borderColor: '#fff',
        };
         
        let attr = {
            color: '#fff',
        };

        return (
            <View key={x.faceId} style={box}>
                <View style={style}></View>
                <Text style={attr}>{x.faceAttributes.gender}, {x.faceAttributes.age} y/o</Text>
            </View>
        );
    });

    return <View>{views}</View>
}



 }
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    alignSelf: 'center',
    backgroundColor: '#ccc'
  },
  button: {
    margin: 10,
    padding: 15,
    backgroundColor: '#529ecc'
  },
  button_text: {
    color: '#FFF',
    fontSize: 20
  }
});
 
export default Detector 

https://i.stack.imgur.com/VTL9K.png

Answer №1

Your component is defined as const Detector = props => { which makes it a function component. Since function components don't have a "this" and don't support methods like setState or componentDidMount, there are two solutions to your problem.

  1. You can create a component that extends from React.Component. Check out the documentation for more details. This way, you'll have access to this and other component methods like this.setState.
  2. Alternatively, you can utilize hooks such as useState to manage state within your components. Refer to the documentation for information on how to use hooks.

The choice between these approaches ultimately comes down to personal preference, although using hooks is considered the "newer" way of handling state in React.

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

Troubleshooting Clarifai object error while invoking "model.predict" within Angular Framework

I've been attempting to utilize Clarifai's color API to extract the different colors present in an image. Unfortunately, I am encountering challenges when trying to call the API, as it consistently returns empty objects. Below is the snippet of ...

Icon for TypeScript absent from npm package listings

Recently, I created a package and uploaded it to the npm repository. The package was displayed with an icon labeled "ts" on the website. https://i.stack.imgur.com/LoY1x.png The accompanying package.json showcased the inclusion of the "ts" icon - https:// ...

Exploring Typescript and Clean Architecture with an In-Memory Database/Repository

Currently, I am integrating clean architecture in my latest project and facing challenges with repositories, data sources, and terminology. My aim is to test my useCases using an in-memory repository as I am only concerned about the business logic at this ...

The HttpPut request code format is malfunctioning, although it is effective for another request

I'm struggling with a HTTPPUT request that just won't get called. Strangely enough, I have a similar put request that works perfectly fine for another tab even though both pages are practically identical. I've exhausted all options and can&a ...

Function exported as default in Typescript

My current version of TypeScript is 1.6.2 and we compile it to ECMA 5. I am a beginner in TypeScript, so please bear with me. These are the imported library typings. The contents of redux-thunk.d.ts: declare module "redux-thunk" { import { Middle ...

Observable in RxJS with a dynamic interval

Trying to figure out how to dynamically change the interval of an observable that is supposed to perform an action every X seconds has been quite challenging. It seems that Observables cannot be redefined once they are set, so simply trying to redefine the ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

Angular D3 - The method 'getBoundingClientRect' is not present in the 'Window' type

Check out this StackBlitz demo I created: https://stackblitz.com/edit/ng-tootltip-ocdngb?file=src/app/bar-chart.ts In my Angular app, I have integrated a D3 chart. The bars on the chart display tooltips when hovered over. However, on smaller screens, th ...

RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this: export function createHTTP(url:string, headers?:Headers){ let injector = ReflectiveInjector.resolveAndCreate([ myHttp, {provide:'defaultUrl ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

A guide on setting the array value on the user interface based on a key within the SectionList

My code is currently retrieving an array value and populating these values based on the key in a SectionList. The keys are displaying properly in the UI, but I am encountering some issues in my render item function, particularly in the second section. Esse ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Please ensure that the property name is a valid type, such as 'string', 'number', 'symbol', or 'any'

Can anyone help me convert this JavaScript file to Typescript? import React, { useState } from 'react'; import { Button } from './Button'; import { Link } from 'react-router-dom'; import './Navbar.css'; import Settin ...

Angular template error: Potential is present but not defined

Encountering an issue with my Angular application's template file (dashboard.component.html). The error message reads "Object is possibly 'undefined'." Here's the portion of the template that seems to be causing the problem: <div> ...

Module `coc-tsserver` not found (error ts2307)

Working on a project using NeoVim with CoC for TypeScript development in a yarn-3 pnp-enabled environment. Suddenly, the editor stopped recognizing imports and started showing errors for non-existent modules (refer to the screenshot). I've already set ...

Can a new class be created by inheriting from an existing class while also adding a decorator to each field within the class?

In the following code snippet, I am showcasing a class that needs validation. My goal is to create a new class where each field has the @IsOptional() decorator applied. export class CreateCompanyDto { @Length(2, 150) name: string; @IsOptional( ...

When I utilize the redux connect function, the class information in my IDE (PhpStorm/WebStorm) seems to disappear

When I use the connect function from redux, it seems to hinder my IDE (PhpStorm) from "Find Usages" on my classes. This is likely because connect returns any, causing the type information from the imported SomeClass file to be lost. export default connect ...

I'm having trouble with VSCode deleting my TypeScript code. Is there a way to disable this feature

My code keeps getting removed and I can't figure out how to stop it. Does anyone know which setting I need to adjust? Watch the video here: This issue occurs in all instances, not just with imports. ...

Efficient ways to manage dropdown cells in ReactGrid

Is there a way to assign individual values to each select element in a cell? I am using ReactGrid with react version 16 There seems to be an issue with the onchange function, and I'm struggling to find help import * as React from "react"; ...

When working with the latest version of Angular CLI, make sure to include a @NgModule annotation in

Just a heads up: I'm diving into Angular for the first time, so bear with me if I make some rookie mistakes. The Lowdown I've got the latest version of Angular CLI up and running The default app loads without a hitch after 'ng serve' ...