Node Red TypeError: Cannot read properties of undefined (reading ‘state’)
I’ve seen that others have had this problem but my situation is a little different.
I have a Node Red function that is attempting to read a helper sensor…
var ha_get = global.get("homeassistant.homeAssistant");
var s1 = ha_get.states["sensor.irrigationsam"].state;
This code is formatted correctly and it does work on rare occasions but most of the time it just doesn’t. I’ve opened up Node Red, ran the function, and I got the correct data. Great! So I immediately try the function again and it fails with the message “TypeError: Cannot read properties of undefined (reading ‘state’)”.
Looking at the homeAssistant object looks like this…
I did notice that my sensor “sensor.irrigationsam” is not in the list. I was never able to see if it was there when the funcion briefly worked. What determines how an entity gets on this list? Could it be that “sensor.irrigationsam” was there but gets released after some timeout? How can I force it into the list?
One thing about HA globals is they are not in alphabetical order and it can be tough to find a specific entity. You can load the global in an inject to see if there is a value. If there is a value, try restarting the nodered addon. As soon as it starts see if the global has a value.
Are you trying to access the state of the entity before it has been loaded in Node-RED from Home Assistant? Does the flow trigger based on a non-Home Assistant event, such as a time-based trigger or immediately after a deploy?
This returned the payload after restarting. I was able to fire it many time with success.
I then fired my function and it returned a value but the second time I tried, it failed.
The inject test also failed after that.
There’s no difference between the two approaches, except that Mikefila’s method handles cases where the entity property is undefined. You can achieve the same result using optional chaining:
var ha_get = global.get("homeassistant.homeAssistant");
var s1 = ha_get.states["sensor.irrigationsam"]?.state;
However, neither method addresses the root issue: the entity doesn’t exist at the time of access, causing s1 to be undefined.