User_3535
User_3535

Reputation: 852

react native getting a error as this.setState is not a function

hi there i"m new to react native during my built process i am getting this error

this.setState is not a function

and my code

type Props = {};
export default class App extends Component<Props> {

componentDidMount(){
 Proximity.addListener(this._proximityListener);
}
 _proximityListener(data) {
   this.setState({
     proximity: data.proximity,
     distance: data.distance // Android-only 
   });
 }


  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
            00
        </Text>
      </View>
    );
  }
}

how to solve this error ? .,

Upvotes: 0

Views: 112

Answers (2)

Rishabh Bhatia
Rishabh Bhatia

Reputation: 1029

Change your componentDidMount function to

componentDidMount(){
  Proximity.addListener(this._proximityListener.bind(this));
}

Upvotes: 1

Alec Lorraine
Alec Lorraine

Reputation: 398

Turn your _proximityListener function into an arrow function like this:

_proximityListener = (data) => {...

This will bind the method to the class and give that method access to the 'this' keyword. :)

Upvotes: 1

Related Questions