Reactjs - getDerivedStateFromProps() not updated the data using setState or Editing the data

Viewed 350

I have to Modify the personal details, I used getDerivedStateFromProps() instead of componentWillReceiveProps() for receiving props. And, to edit the username, name, and set the state to update the personal data. It's should not be updated.

I have added the below codes.

Constructor

constructor(props){
    super(props)
    this.state = {
        name : '',
        username : '',
        email : ''
    }
    this.props.getPersonal(userId)
}

If I using componentWillReceiveProps, it's working fine

static componentWillReceiveProps(nextProps) {
        if(this.state.username !== nextProps.personal.username){
            this.setState({username: nextProps.personal.username})
        }
    }

If I using the getDerivedStateFromProps

static getDerivedStateFromProps(props, state) {
        if (props.personal.username !== state.username) {
          return {
            username: props.personal.username
          };
        }
        return null;
      }

updating the state

handleChange = e => {
          const { name, value } = e.target;
          this.setState({ [name] : value})
      }

Render method

render(){
    const { username, name } = this.state
    return (
        <div>
            <div className="form-group  m-t-40">
                  <div className="col-xs-12">
                    <input className="form-control" type="text" name="username" placeholder="Email" value={username} onChange={this.handleChange} />
                  </div>
                </div>
        </div>
    )
}

I tried ReactJs 13.1 and I hope you help me out for anyone.

2 Answers

You can do this in the constructor:

constructor(props){
    super(props)
    this.state = {
        name : props.personal.name,
        username : props.personal.username,
        email : props.personal.email
    }
}

or in componentDidMount to have fresh parent data on next mount

componentDidMount = () => {
   this.setState({
     name : this.props.personal.name,
     username ....
   })
}

and not use getDerivedStateFromProps()

I think you have to use getDerivedStateFromProps with shouldComponentUpdate(nextProps, nextState) or componentDidUpdate(prevProps, prevState). getDerivedStateFromProps is for modifying data before set the state, I think

Related