Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use conditional operator in react js [duplicate]

In many places I'm setting modified by, created by etc:

const test = this.state.isValueEdited
? {
  modifiedById: getLoggedInUser().userId,
}
: {
 // TODO
};

How could I check if getLoggedInUser has some value, than access .userId.. otherwise lets set null.

Thanks

Cheers

like image 329
Roxy'Pro Avatar asked Nov 05 '25 01:11

Roxy'Pro


2 Answers

Also using the ternary operator

 modifiedById: getLoggedInUser() ? getLoggedInUser().userId : null

To avoid executing twice

const evaluation = getLoggedInUser()

{modifiedById: evaluation ? evaluation.userId : null}
like image 69
Dupocas Avatar answered Nov 06 '25 16:11

Dupocas


You can use logical OR ||

modifiedById: ( getLoggedInUser() || { userId: null } ).userId

When the value returned from the getLoggedInUser returns falsy value the {userId : null} will act as default value

This expects value returned from getLoggedUser is falsy value in case it fails the condition

like image 24
Code Maniac Avatar answered Nov 06 '25 16:11

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!