0

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!

Xan
  • 74,770
  • 16
  • 179
  • 206
Karthik Samyak
  • 467
  • 2
  • 8
  • 19
  • 1
    Also related: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – Makyen Aug 24 '17 at 18:03

1 Answers1

3

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');
  });      
})