Shashika Virajh
Shashika Virajh

Reputation: 9457

Having more than one condition in getDerivedStateFromProps in React

In my React application, I have the following code.

state = {
   credentialDeletion: false,
   accountDeletion: false
}

static getDerivedStateFromProps(nextProps) {
   if (nextProps.accountDeleting) {
      return {
         accountDeletion: true
      }
   }

   if (nextProps.credentialDeletion) {
      return {
         credentialDeletion: true
      }
   }

   return null;
}

But this code doesn't work properly. If I remove one condition, then the other works fine. But together, only the first condition works. How should I write this code properly?

Upvotes: 2

Views: 513

Answers (1)

Tholle
Tholle

Reputation: 112787

You could create an object that you add properties to in each if statement and return that, so that both if statements will be run.

static getDerivedStateFromProps(nextProps) {
  const update = {};

  if (nextProps.accountDeleting) {
    update.accountDeletion = true;
  }
  if (nextProps.credentialDeletion) {
    update.credentialDeletion = true;
  }

  return update;
}

Upvotes: 4

Related Questions