4

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

Dupocas
  • 20,285
  • 6
  • 38
  • 56
Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102

3 Answers3

3

Also using the ternary operator

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

To avoid executing twice

const evaluation = getLoggedInUser()

{modifiedById: evaluation ? evaluation.userId : null}
Dupocas
  • 20,285
  • 6
  • 38
  • 56
3

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

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • can you explain this line please `getLoggedInUser() || { userId: null }` This means even if userId is null try to access it ? or ? – Roxy'Pro Sep 04 '19 at 17:20
  • Neat! Not the biggest fan of this syntax but it sure gets the job done – Dupocas Sep 04 '19 at 17:22
  • @Roxy'Pro when the value returned from the `getLoggedInUser` is falsy than only `{userId: null}` will come into picture, logical OR start evaluating expression from left and stop once it finds true value, if none of the value is true it returns the last value from expression, so here in `getLoggedInUser` returns falsy value than only the `{userId: null}` will be used else the value returned from function will be used – Code Maniac Sep 04 '19 at 17:23
  • Down voter care to comment :/ – Code Maniac Sep 04 '19 at 17:45
2

You can retrieve the user first, then you can use the && operator to get the userId only if user returns truthy. false, null, undefined, "", 0, NaN are falsy values

const user = getLoggedInUser() || null;

const test = this.state.isValueEdited ? ({
  modifiedById: user && user.userId,
}) : ...

If getLoggedInUser already returns null when the user is not logged, you can omit the || null

Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56