Set switch on/off and save each change to the collection.

Hi guys,

I have a button that when I click it it turns a switch on, then waits 5 minutes and the switch turns back to false. I would like to save each change to the database but it’s only saving the first change.

Example of what I want: I click the button, switch is on, I can see the box checked in the collection for 5 minutes, then after 5 minutes the switch turns off and I can see the box without check mark in the collection until the button is clicked again.

This is a member page and the switch is connected to the dataset.

This is my code:

export function button30_click(event) {
    $w('#dataset1').setFieldValue("newBoolean", true);
    $w('#dataset1').save();
    
    setTimeout(function () {
        $w('#dataset1').setFieldValue("newBoolean", false);
    }, 300000);
    $w('#dataset1').save();

}

Thank you very much for your help.

Hi Omar,

Though there may be other ways to do it, having the setTimeout function call an async function will achieve your desired result.

export function button30_click(event) {
  ChangeSwitchValue(true);
  setTimeout(function () {ChangeSwitchValue(false)}, 300000);
}

export async function ChangeSwitchValue(newValue){
  await $w('#dataset1').setFieldValue("newBoolean", newValue);
  await $w('#dataset1').save();
  console.log("data saved");
}

Thanks! I’ll give it a try.

Additional to Anthony’s reply, you could take a look at one of the examples on my site…
https://russian-dima.wixsite.com/meinewebsite/switch-safe-function

import wixData from 'wix-data';

//------------------------------------ USER-DATA-INTERFACE -----------------------------------------
//var DATABASE =    "Switch-Save-Function"
var DATASET =   "dataset1"
//------------------------------------ USER-DATA-INTERFACE -----------------------------------------
var currentItemIndex

$w.onReady(function () {
    $w("#"+DATASET).onReady( () => {
        $w('#TXTmember').text="Member-"+currentItemIndex
        $w('#BTNsave').onClick(()=>{
 if ($w('#BTNswitch1').checked===true){$w("#"+DATASET).setFieldValue("btnStatus", true);}
 else {$w("#"+DATASET).setFieldValue("btnStatus", false);}
            $w("#"+DATASET).save();
        })

        $w('#BTNnext').onClick(()=>{console.log("NEXT")
            currentItemIndex = $w("#"+DATASET).getCurrentItemIndex()+1
            console.log(currentItemIndex)
            $w('#TXTmember').text="Member-"+currentItemIndex
        })

        $w('#BTNprevious').onClick(()=>{console.log("PREVIOUS")
            currentItemIndex = $w("#"+DATASET).getCurrentItemIndex()+1
            console.log(currentItemIndex)
            $w('#TXTmember').text="Member-"+currentItemIndex
        })
    })
});