Reputation: 809
I am trying to store an object, mapping a string to a list, using chrome.sync.get
. My goal is to create a new list for a non-existing key or append an element to the list if the key exists. However, I am unable to populate the object. When I try to retrieve the values I have previously inserted, I get an empty Object as the returned value. Following is the code I am using:
let currentTabId = '234';
let spawnedTabId = '390';
chrome.storage.sync.get(currentTabId, function(data) {
if (typeof data.currentTabId === 'undefined') {
chrome.storage.sync.set({currentTabId: [spawnedTabId]}, function() {
console.log("Initialized "+currentTabId+" with "+spawnedTabId);
});
chrome.storage.sync.get(currentTabId, function(data) {
console.log(data);
});
} else {
data.currentTabId.push(spawnedTabId)
chrome.storage.sync.set({currentTabId: data.currentTabId}, function() {
console.log("Appended "+spawnedTabId+" to "+currentTabId);
});
}
});
The output I am getting is:
>>> Initialized 234 with 390
>>> {}
__proto__: Object
Upvotes: 0
Views: 262
Reputation: 73856
The code had three mistakes:
{variable: value}
it should be {[variable]: value}
, more infoobj.variable
it should be obj[variable]
let key = '234';
let spawnedTabId = '390';
chrome.storage.sync.get(key, data => {
const spawned = data[key] || [];
spawned.push(spawnedTabId);
chrome.storage.sync.set({ [key]: spawned }, () => {
// now you can read the storage:
// chrome.storage.sync.get(key, console.log);
});
});
Upvotes: 1