Rasmus Hye
Rasmus Hye

Reputation: 33

Is it possible to access other state values in same constructor?

Is it possible to access a state value in constructor, and use it in a different state value in same constructor? See example below.

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      values1: {
        value1: "value 1"
      },
      values2: {
        value2: "value 2"
      },
      selected: {
        selectedValue: `Selected value is: ${this.state.values1.value1}`
      }
    }
  }
}

Upvotes: 0

Views: 64

Answers (3)

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

Yes, you approach will work with small modification. state is plain JavaScript object, so you may assign new properties to it several times in constructor.

constructor () {
    super ();
    this.state = {
        values1: {
            value1: "value 1"
        },
        values2: {
            value2: "value 2"
        }
    }
    this.state.selected = {
        selectedValue: "Selected value is: " + this.state.values1.value1
    }
}

And sample

Upvotes: 0

TheLeftRight
TheLeftRight

Reputation: 33

Yes it is but you would have to use the setState() method to do so

You would declare the selected state above then within the constructor you could then usethis.setState({selected: this.state.values1.value1}) to set the state.

Upvotes: 0

Alok Mali
Alok Mali

Reputation: 2881

It will not work. But you can set another variable's value in componentDidMount.

See my example :

class App extends Component {
    constructor(props){
      super(props);
      this.state = {
        values1: {
          value1: "value 1"
        },
        values2: {
          value2: "value 2"
        },
      }
    }

    componentDidMount(){
      this.setState({selectedValue: "Selected value is: "+ this.state.values1.value1}); 
    }


    render() {
      return (
        <div>
          <p>
            {this.state.selectedValue}
          </p>
        </div>
      )
    }
  }

Here is a working example - https://stackblitz.com/edit/react-2ra5ht

Upvotes: 3

Related Questions