Reputation: 707
I am trying to update state in react native component. But its getting errors, Could someone help me.
I'm using react-native-cli verions: 2.0.1 react-native verions: 0.55.4
Here is my code:
import React, { Component } from 'react'
import {
Button,
Text,
View,
} from 'react-native';
export class ToggleButton extends Component {
state = {
isDone: false
};
onAction() {
const value = !this.state.isDone;
this.setState({ isDone: value });
const newValue = this.state.isDone;
console.log(newValue);
}
render() {
return (
<View>
<Button
title="Action"
onPress={this.onAction}
/>
</View>
)
}
}
export default ToggleButton;
Upvotes: 2
Views: 1858
Reputation: 703
Below is the solution
import React, { Component } from 'react'
import {
Button,
Text,
View,
} from 'react-native';
export class ToggleButton extends Component {
// Add state in constructor like this
constructor(props){
super(props);
this.state = {
isDone: false
};
}
onAction() {
const value = !this.state.isDone;
this.setState({ isDone: value });
const newValue = this.state.isDone;
console.log(newValue);
}
render() {
return (
<View>
<Button
title="Action"
// Add function with onPress
onPress={() => this.onAction}
/>
</View>
)
}
}
export default ToggleButton;
Upvotes: 0
Reputation: 1661
Change
onPress={this.onAction}
to
onPress={this.onAction.bind(this)}
Check: this
Upvotes: 1
Reputation: 2371
You have three different solutions.
The problem is that you're loosing the reference to this
, because the function is not executed in the original context, so this.setState
is not a function, but a undefined.
In this page there are examples for all of the approaches: https://reactjs.org/docs/handling-events.html
Upvotes: 1