Bhaumik Surani
Bhaumik Surani

Reputation: 1833

react native one variable update is other variable value

I want to store one state variable value temporarily and change in only temporarily variable.

in my code original variable is var1 and temp variable is var2.

After update var2 value var1 value is automatically update.

Before update var2 value:-

enter image description here

After update var2 value:-

enter image description here

My Code:-

class DemoScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            var1: {
                data:'variable 1 Data'
            },
            var2: {
                data:'variable 2 Data'
            }
        }
    }

    componentDidMount() {
        alert("var1 : " + this.state.var1.data + "\nvar2 : " + this.state.var2.data);
        this.setState({var2:this.state.var1});
    }

    render() {
        return(
            <View style={styles.container}>
                <TouchableOpacity
                    onPress={()=>{
                        var var2 = this.state.var2;
                        var2.data = "value changed";
                        this.setState({var2:var2});
                    }}>
                    <Text>Change Value for var2</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={()=>{
                        alert("var1 : " + this.state.var1.data + "\nvar2 : " + this.state.var2.data);
                    }}>
                    <Text>Display Values</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

why it is happening?
how to solve it?

Upvotes: 0

Views: 781

Answers (1)

Tareq El-Masri
Tareq El-Masri

Reputation: 2573

I think what happens here is that you're setting var2 to the reference of var1 not its value, that's why that happens, what you need to do is to replace that line

this.setState({var2:this.state.var1});

With this line:

this.setState({var2: Object.assign({}, this.state.var1)});

Using Object.assign will clone the value of your object without returning its reference. Always remember Obj1 = Obj2 means that Obj1 equals the reference of Obj2 which means that the both of them considered the same object

Upvotes: 1

Related Questions