Is there any life cycle method for understand the new state key added to component state?

73 views Asked by At

UPDATED:

I have a question for you. In my react app I have basic state like below.

constructor(props){
    super(props);
    this.state = {
        title: "Hello";
    }
}

And think that I have button and onClick event I add new dynamic key to state. Let's say [key] = "newValue" and "val"= 1.

onClickEvent(){
    let splitArray = value.split('_');
    let key = splitArray[0];
    let val = splitArray[1];
    this.setState({
        [key]: val
    });
}

render(){
        return(
        <div>
            <button onClick={this.onClickEvent}>Click</button>
             <input value={} />
        </div>
        );
}

Everything is Ok until now. But I don't know how to use this dynamically created new state property which in case my example [key].

In render method, my input value is empty because I don't have value in the state.

After the click event, I add new state key and I want that my render like this.

render(){
        return(
        <div>
            <button onClick={this.onClickEvent}>Click</button>
            <input value={this.state.[key]} />
        </div>
        );
    }

Is there any life cycle method of react component, detects the added new state property ? Because I want to use that newly created state property.

I hope my question is clear.

4

There are 4 answers

2
Dan Prince On

Store the key in your state too.

this.setState({
  [key]: val,
  updatedKey: key
})

Then you can implement componentDidUpdate and use the key to read the new state value.

componentDidUpdate() {
  let { updatedKey } = this.state;
  let val = this.state[updatedKey];
}
0
Joey van Breukelen On

Take a look at: https://reactjs.org/docs/react-component.html#componentwillreceiveprops

You could use the following

componentWillReceiveProps(nextProps){
      ...
    }
0
Gopikrishna S On

You don't need a life cycle method to get that value, put the key in the state as well:

onClickEvent(){
    const [currentKey, value] = value.split('_');
    this.setState({
        currentKey,
        [currentKey]: val
    });
}

and access it in the next render cycle with:

this.state[this.state.currentKey];
1
godsenal On

I think ComponentDidUpdate is what you are looking for. You can detect new key of state like this.

componentDidUpdate(prevProps, prevState){
  var prev = Object.keys(prevState).sort();
  var current = Object.keys(this.state).sort();
  if(JSON.stringify(prev) === JSON.stringify(current)){
    do something
  }
}