Damodar
Damodar

Reputation: 707

React native set state is not working

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

Answers (3)

GAURAV
GAURAV

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

angelos_lex
angelos_lex

Reputation: 1661

Change

    onPress={this.onAction} 

to

    onPress={this.onAction.bind(this)}

Check: this

Upvotes: 1

Ivan Beldad
Ivan Beldad

Reputation: 2371

You have three different solutions.

  1. Bind your function in the constructor.
  2. Use the experimental public class fields syntax.
  3. Pass a lambda to executing your function.

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

Related Questions