Node-RED - Variable Set Not Setting

59 Views Asked by At

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:

  • different datatypes to bool & number but hasn't changed at all
  • inserting an only 1 output
1

There are 1 best solutions below

0
hardillb On BEST ANSWER

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
}