javascriptnode.jsnode-red

Node-RED - Variable Set Not Setting


The Code Overall is to act as a switch making it saying if its 'hit'. The switch activates once until needing to reset. However, the hitobject or reset isn't restarting thus activating hit repeatedly if payload is true.

How can I fix it so it requires a false in payload to be active again

var hitobject = context.get("hitojbect") || true;

if (msg.payload == true && hitobject == true) {
  hitobject = false;
  context.set("hitobject", hitobject);
  console.log("Hit");
} else if (msg.payload == false && hitobject == false) {
  hitobject = true;
  context.set("hitobject", hitobject);
  console.log("Not Hit");
}

return;

I tried:


Solution

  • Your first line will always evaluate to true

    var hitobject = context.get("hitojbect") || true;
    

    Because if you store false it will always trip the or and set the value to true.

    Try

    var hitobject = context.get("hitojbect")
    if (hitobject === undefined) {
      hitobject = true
    }