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

0

3 Answers 3

3

Also using the ternary operator

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

To avoid executing twice

const evaluation = getLoggedInUser()

{modifiedById: evaluation ? evaluation.userId : null}
Sign up to request clarification or add additional context in comments.

1 Comment

This will call getLoggedInUser() twice. Thats inefficient & might cause unwanted sife effects.
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

4 Comments

can you explain this line please getLoggedInUser() || { userId: null } This means even if userId is null try to access it ? or ?
Neat! Not the biggest fan of this syntax but it sure gets the job done
@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
Down voter care to comment :/
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.