Node Red => TypeError: Cannot read properties of undefined (reading 'state')

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?

My server configuration looks like this…

Any help would be appreciated.
Thanks

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.

homeassistant.homeAssistant.states["sensor.irrigationsam"].state

image

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?

For testing I was using an inject to trigger the function.

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.

I think my function is breaking it.

This pulls in the entire global object. I believe at one time it was required but you can now just get the one value direct try

let s1 = global.get('homeassistant.homeAssistant.states["sensor.irrigationsam"].state')

Switching to this method seems to work consistently. I guess grabbing all entities is not a good thing.

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.