[Solved] How do save switch state?

Hello guys,

I created an app that I can use to switch on/off appliances using FIrebase and Arduino.

My issue is this: After toggling the switch and I leave the screen that has the switch button, maybe by pressing the back button or navigating to another screen (still within the same session). By the time I launch the screen with the switch again, its status automatically turns to FALSE (the default status), the same thing happens if my Switch value is set to default TRUE in my block properties, the switch status automatically turns to TRUE too.

This does not affect the actual function, i.e the switch toggling automatically to FALSE doesn’t switch off the device it’s controlling

Please, help

2 Likes

Hi, @olasupoayobami02fa! :wave:

This will always happen, because every time, the screen initializes, it starts freshly - that’s why, the switch is returned to default set value.

To prevent this, try following these steps -

  • Since you are saving the switch's value in realtimeDB, you would need to check that value every time the screen is opened - and set switch’s value accordingly.
    But, getting a value from Firebase every time the screen is opened, would not be efficient. Therefore, along with saving in Firebase, save the value in LocalStorage too.
  • After saving in LocalStorage, it would be efficient for us to get the value every time (because since it’s stored locally, the retrieval time would be much less).
  • Next, grab a screen Opens event block, and a Local Storage - get block. After getting the value, set the switch’s value to the value.

Your final blocks should look like this - (I have reduced the number of blocks to the minimum required for proper functionality)

Hope I helped you. :slightly_smiling_face:

Good Luck! :+1:
Thanks! :blush:

3 Likes

Thanks so much @kartik14

I’m setting this up but I have another slight issue. I can’t set my switch's value to value as you did here

Here’s mine: I can only toggle between true and false Mine

3 Likes

Hi, @olasupoayobami02fa! :wave:

Just drag the small green value block, and attach to the dark green from Switch13 set value to block.

Thanks! :blush:

3 Likes

Works perfectly.

Thank you! :star_struck:

1 Like

Glad I helped you :blush:

Happy Thunking! :tada:
Thanks! :blush:

1 Like

Where do you get the “error” block?

Error blocks are built-in to certain blocks. So if you’re using a Realtime_DB block, you’ll see it’s already attached. But you can also save Firebase values using cloud variables and paths. So it’s not necessary to do that anymore.

1 Like

How do I do this now that the old Thunkable System has changed?
I want to create a dark mode for my app.

Thank you!