0

I have a very basic question but I couldn't find any similar questions. I have the following code:

var admin_li = helper.h('li', [fpu_link('/admin', 'control', false)]);
if (Discourse.User.current().admin) {
    menu_li.push(admin_li);
}

I get the following error in the DevTools:

 Uncaught TypeError: Cannot read property 'admin' of null

How can I check if the Discourse.User.current() has a property/method of admin in the if statement?

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
abuka123
  • 441
  • 3
  • 12
  • Possible duplicate of [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – Heretic Monkey Jun 04 '19 at 23:53
  • I don't think I've ever seen a method chained with a property? `Discourse.User.current().admin` or is it `Discourse.User.currentProp()` or `Discourse.User.current('admin')`? – zer00ne Jun 04 '19 at 23:54
  • 1
    @zer00ne `if(document.getElementById('foo').classList.contains('bar') === false) { }` you see it every day. – Kaiido Jun 04 '19 at 23:58
  • 1
    @Kaiido derp indeed I do, the obvious is always the least remembered. – zer00ne Jun 05 '19 at 00:48

1 Answers1

1

Something along the lines of this should work for you:

var admin_li = helper.h('li', [fpu_link('/admin', 'control', false)]);
// Get current from user and store in local variable
var currentUser = Discourse.User.current();

if(currentUser !== null && currentUser !== undefined) {
  // If currentUser not null and not undefined then it's safe to access
  // the admin field
  if (currentUser.admin) {
    menu_li.push(admin_li);
  }
}

Alternatively (as suggested by @MarkMeyer), the code above can be written in a more concise shorthand form as follows:

if(currentUser && currentUser.admin) {
  // If currentUser is "truthy" (not null, not undefined, etc), and 
  // currentUser.admin is "truthy", then update menu_li list
  menu_li.push(admin_li);
}

See this more information on the definition of "truthy" (and "falsey") values in JavaScript

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65