Reputation: 159
So, I'm trying to follow this https://developer.chrome.com/extensions/storage#property-local documentation, but value[category] isn't being updated by the set operation, anybody know what's going on here? g is a global object and g[category] increments to a click event.
//assume someNum has already been stored as a 0
var g = {someNum:0};
var category = "someNum";
g[category]++;
chrome.storage.local.set({category:g[category]}, function () {
console.log(g[category]); // 1
chrome.storage.local.get(category, function (value) {
console.log(value[category]); // 0
});
});
Upvotes: 2
Views: 9290
Reputation: 1219
The chrome.storage calls are asynchronous. You need to place the get call inside the callback function of the set call.
Nothing wrong with the api, I use it in most of my extensions.
Here's an example that works for me in dev console:
var randm = Math.random();
console.log("pre: " + randm);
chrome.storage.local.set({r: randm}, function(){
chrome.storage.local.get("r", function(st){
console.log("post: " + st.r);
randm = 1;
console.log("are they the same? " + (st.r == randm ? "yes" : "no"));
});
});
Your code also runs for me as below:
chrome.storage.local.set({category:g[category]}, function () {
console.log(g[category]); // 1
chrome.storage.local.get("category", function (value) {
console.log(value.category); // 1
});
});
Upvotes: 5
Reputation: 889
Since category
is a variable (in your case, var category = "someNum"
), you need to use:
chrome.storage.local.set({[category]: g[category]}, function() {...
or (if you use Chrome before 2016)
var obj={};
obj[category] = g[category];
chrome.storage.local.set(obj, function() {...
Upvotes: 4
Reputation: 306
Those get
and set
functions are asynchronous. If you call chrome.storage.local.get
from within the callback from set
, do you still have this problem?
Upvotes: 1