NateDhaliwal is encountering a ReferenceError: iconName is not defined when using @tracked in a Discourse component. The code initializes iconName based on a setting and then uses it to generate an icon using iconNode. NateDhaliwal includes code snippets for comparison, showing a working @tracked variable in another component. merefield suggests that tracking iconName is unnecessary because it’s likely to be constant and advises using DIcon instead with {{icon this.myIcon}} as an example, referencing merefield’s chatbot component. merefield emphasizes the resource cost of unnecessary tracking, and points out that settings are unlikely to be updated without a page refresh. NateDhaliwal thanks merefield for the advice. Later, NateDhaliwal asks for help with a function ifProtected and how to return an icon within it, ultimately resolving the issue by directly using {{icon this.iconName}} within a <template> and initializing iconName as a constant.
import { apiInitializer } from "discourse/lib/api";
import { iconNode } from "discourse-common/lib/icon-library";
import { tracked } from "@glimmer/tracking";
export default apiInitializer((api) => {
@tracked iconName = settings.category_lock_icon || 'lock'; // Fallback to 'lock' if setting is not defined
@tracked lockIcon = iconNode(this.iconName);
Frustratingly, the browser console tells me that ReferenceError: iconName is not defined. Looking at the file in the browser dev tools, this is what it looks like:
iconName = settings.category_lock_icon || 'lock'; // Fallback to 'lock' if setting is not defined
lockIcon = (0, _iconLibrary.iconNode)((void 0).iconName);
This, compared to another component I made that uses tracked variables (which works):
You don’t need to track these. They will be constant so unnecessary. You only need to track things that will be dynamic and with which you want to re-fire getters.
Every time you track you use resources so keep that to minimum. It’s no big deal but good practice not to track if something won’t change during a page visit.
I don’t believe settings will be updated without a page refresh in any case.
const iconName = settings.category_lock_icon || 'lock'; // Fallback to 'lock' if setting is not defined
const lockIcon = <template>{{icon this.iconName}}</template>