Mederic
Mederic

Reputation: 2019

_this.setState is not a function

currently learning about react-native and trying out to code a few things I came across this error:

_this.setState is not a funtion.(In '_this.setState({myState: createSignature()})','_this.setState' is undefined)

I have routing and get my about page like this:

import React from 'react'
import { TouchableOpacity, Text, View } from 'react-native'
import { Actions } from 'react-native-router-flux'
import Moment from 'react-moment';
import EventEmitter from "react-native-md5";
import md5 from "react-native-md5";

const devID = 0000;
const authKey = "XXXXXXXXXXXXXXXXXXX";

function createSignature(){
    var ut = new Date();
    var time = <Moment utc={true} element={Text} format="YYYYMMDDHHmmss">{ut}</Moment>;
    var signaturePre = devID + "createsession" + authKey + time;
    return md5.hex_md5(signaturePre);
}

const About = () => {
   const goToHome = () => {
      Actions.home()
   }   

state = {
      myState: 'Lorem ipsum dolor sit amet,'
   }
   updateState = () => {
      this.setState({ myState: createSignature() })
   }
      return (
         <View>
            <Text onPress = {this.updateState}>
               {this.state.myState}
            </Text>
            <TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>
                <Text>This is ABOUT</Text>
            </TouchableOpacity>  
        </View>
  )
}
export default About

I don't want someone to just give the solution I want to understand what I'm missing I have also tried using Props for it but this resulted in the same error.

The error hints to line 29

return(

Upvotes: 1

Views: 828

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

Your About component is a functional component and hence don't have the this property and state. Create it by extending React.Component

class About extends React.Component {
   goToHome = () => {
      Actions.home()
   }   

   state = {
      myState: 'Lorem ipsum dolor sit amet,'
   }
   updateState = () => {
      this.setState({ myState: createSignature() })
   }
      return (
         <View>
            <Text onPress = {this.updateState}>
               {this.state.myState}
            </Text>
            <TouchableOpacity style = {{ margin: 128 }} onPress = {this.goToHome}>
                <Text>This is ABOUT</Text>
            </TouchableOpacity>  
        </View>
  )
}
export default About

Upvotes: 3

Related Questions