Human Code
Human Code

Reputation: 93

Updating changed value on user interface

I want my value to change on the screen when button is pressed. It does change the variable value behind the scenes but has no effect for the outdated value shown on the screen.

export default class App extends Component {
render() {
this.state = {
  myVariable: 'egs'
}
const changeValue = () => {
  this.state.myVariable = "CHANGED??!!"
}
return (
  <View style={styles.container}>
    <Text>
      {this.state.myVariable}
    </Text>
    <Button onPress={changeValue} title="CHANGE IT"/>
  </View>
);
}
}

I expect to update value to the changed one instead of outdated one.

Upvotes: 0

Views: 46

Answers (2)

Willman.Codes
Willman.Codes

Reputation: 1413

Move state initialization outside of render as well as the changeValue method

You also cannot mutate statue directly, instead use setState()

This should work:

export default class App extends Component {
    state = {
        myVariable: 'egs'
    }
    changeValue = () => {
        this.setState({myVariable:"CHANGED??!!"})
    }
    render() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.myVariable}
                </Text>
                <Button onPress={changeValue} title="CHANGE IT"/>
            </View>
        );
    }
}

Upvotes: 2

this.state.myVariable = "CHANGED??!!"

change to

this.setState({ myVariable: "CHANGED??!!" })

Upvotes: 0

Related Questions