Samyak Samyak - 1 month ago 8
Javascript Question

How to negate a variable which is in chrome.storage.local

I need to negate/toggle the boolean value of a variable which is in chrome.storage.local but it's throwing an error:

var toggle = chrome.storage.local.get('toggle');
chrome.storage.local.set({ "toggle": !toggle }, function() {
console.log('Settings saved');
});


I tried getting the variable first but it's showing an error: Invocation of form get(string) doesn't match definition get(optional string or array or object keys, function callback).
Any help appreciated!

K3N K3N
Answer Source

Since reading is asynchronous we need to use a callback (hence the error message):

chrome.storage.local.get("toggle", function(data) {               // async callback
  // check for errors via runtime.lastError

  // update settings
  chrome.storage.local.set({"toggle": !data.toggle}, function() { // invert and set
    // check for errors via runtime.lastError
    // Notify that we saved.
    console.log('Settings saved');
  });      
})