Checking for string, nested states throws undefined error


Here es what I am trying to do:

  • I have a nested statemachine (smxstate node).
  • Depending on the state, I need to enable disable buttons in the dashboard

The (reduced) code I have is:

if (msg.payload.state == "idle"){ 
    return [ 
        {enabled: true}, // Button 1
        {enabled: true}, // Button 2
        {enabled: true}, // Button 3
} else if (msg.payload.state.nested1 == "state_xy") {
    return [
        {enabled: true}, // Button 1
        {enabled: false}, // Button 2
        {enabled: false}, // Button 3
} else {
    return [
        {enabled: false}, //Button 1
        {enabled: false}, //Button 2
        {enabled: false}, //Button 3

The code works as intended. But whenever the nested criteria is false i get TypeError: Cannot read property 'nested1' of undefined. I don't know if the same would happen for non-nested criteria as the only non-nested one is the "idle" one.

As I said the whole code is working but i have a ton of messages in the debugging-message window, which makes it hard to debung non-working stuff.

Thank you for your time and effort helping the community and noobs like me.

For starters, it is much better to get into the habit of using exact comparitors for if statements with === rather than ==.

Secondly, while you've not shared any example data, I'm guessing you have a msg coming through that does not have a msg.payload.state at all. Maybe msg.payload is a string rather than an object? You need to exclude that from your if's.

Thank you for the good practice input!

Bullseye!! I have the state machine firing off a second message, which I momentarily forgot.

Thanks a lot!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.