Multiple props validation in getDerivedStateFromProps in react js

Viewed 2264

I am trying to upgrade my react version from react 15 to 16 so while doing that am facing one challenge in getDerivedStateFromProps . In ComponentWillReceiveProps ,

componentWillReceiveProps(nextProps) {

  if (nextProps.postDetails !== []) {
    this.setState({
      postDetails: nextProps.postDetails
    });
  }

  if (nextProps.userData.length === 2) {
    this.setState({
      userData: nextProps.userData
    });
  }
}

// in the above am checking two different props and setting the value accordingly

In getDerivedStateFromProps ,

static getDerivedStateFromProps(props, prevState) {
    if (prevState.value !== props.value) {
      return {
        value: props.value
      }
    }
  }
  //here the problem is ,am unable to do multiple props validations here
  

my question here is , as i did in componentWillReceiveProps how to do multiple props validation in getderivedstatefromprops . Can someone clarify me on this .

I tried like this below, but it is not coming to next if !!!

let xx = true;
let yy = true;
if (xx) {
  console.log("if 1");
  return {
    value: nextProps.someValues,
  };
}
if (yy) {
  console.log("if 2");
  return {
    value2: nextProps.someValues2,
  };
}

expected o/p two console logs but am getting 1st if console only !!

1 Answers

just use intermediate variable to stack the changes

getDerivedStateFromProps(props, state) {
    let update = {};

    if (props.postDetails !== []) {
        update.postDetails = props.postDetails;
    }

    if (props.userData && props.userData.length === 2) {
      update.userData = props.userData;
    }

    return update;
}

As suggests @V-SHY it makes sense to ensure if we have at least one property me need to provide. Otherwise we better return null to avoid unnecessary re-rendering.

return Object.keys(update).length ? update : null;
Related