0

I want to use the same modal dialog for both editing and adding. I was previously using componentWillReceiveProps and setting the new state with props. However I read that it is being deprecated. I tried to use getDerivedStateFromProps but it behaves differently.

My old code was something like below

  componentWillReceiveProps(nextProps) {
    if (nextProps.original) { // Are we editing?
      const item = nextProps.original;
      this.setState({
        name: item.name,
        slug: item.slug
      });
    } else {
      this.setState({ // Fresh
        name: null,
        slug: null
      });
    }
  }

With above code, whenever the props change I was resetting the modal window with new state. Same code doesn't work for getDerivedStateFromProps My only solution is adding a key with String(new Date().getTime()) to my modal component so that each time I open the modal, it resets its state.

My Questions are;

  • Should I keep using componentWillReceiveProps if I am using "react": "16.8.3" with "react-native": "0.59.9" ?
  • Is it okay to reset my modal by using a key? If not what is a better way to reset it for add/edit?

1 Answer 1

1

In the grand scheme of things, I think it will be in your best interest to move on from the soon deprecated methods. You can likely replicate the same behavior using componentDidUpdate() instead, which captures the prevProps, which you can use to compare to the new props.

  componentDidUpdate(prevProps) {
    if (prevProps.original !== this.props.original) { //update state if different
      const item = this.props.original;
      this.setState({
        name: item.name,
        slug: item.slug
      });
    } else {
      this.setState({ // Fresh
        name: null,
        slug: null
      });
    }
  }

Here's a sandbox as well for reference on how you can create edit functionality from inside a modal: https://codesandbox.io/s/awesome-maxwell-qh76t

Sign up to request clarification or add additional context in comments.

4 Comments

I don't know why but above approach leads to Maximum update depth exceeded error. I see that componentDidUpdate and render methods call one after another.
That will happen if you call something that updates your state inside the render(). I probably can give you a better demonstration through a sandbox, let me upload one for you.
@Meanteacher just made a sandbox for you, let me know if you have any questions :)
Thank you so much! I will play with it and ask you if I don't get it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.