0

I have two components. Child component will open in modal box. Modal box component will contain add and edit the user. I have passed some values for modal box input and getting that value in getDerivedStateFormProps life cycle hook. Initially it's populating the value to input value. But after that if type anything in the text box state is not updated. Please see the details below

static getDerivedStateFromProps(props, state) {
    state.show = props.show;
    state.company = props.company;
    return state;
  }
onChange = async(e) => {
    this.setState({company: {...this.state.company, [e.target.name]: e.target.value}});
  }

But the state is not updating. Could anyone please provide help to resolve the issue. Thanks in advance.

az rnd
  • 643
  • 3
  • 14
  • 28

1 Answers1

0

Don't mutate the state parameter.

The correct usage of getDerivedStateFromProps is to return an object which is shallow-merged into the component's existing state.

static getDerivedStateFromProps(props) {
    const {show, company} = props;
    return {show, company};
}

Also, getDerivedStateFromProps will be called by React after applying state from your call to this.setState. That means any change to company in getDerivedStateFromProps will clobber the change to company in this.setState.

Steve
  • 8,066
  • 11
  • 70
  • 112
  • Sure, but I have shown you how to use `getDerivedStateFromProps` correctly. Most likely the cause of your non-working code lies within the code you have **not** posted in the question. – Steve Aug 24 '19 at 13:41