0

I'm trying to integrate chrome's storage into my extension. And I'm having trouble grasping how the data is stored once it's written because nothing I try seems to work. What I want to be able to do is store an object with a specific key. But that key is generated runtime, dynamically.

So I have something like this so far.

 let storage = {};
storage["status"] = "no status";
chrome.storage.local.set(storage,function(){

});

When I do that, the key automatically becomes 'storage' but I don't want to do that. Because I want the key to be unique every time. So ideally what I want to do is this

let storageid = generateid();//generate unique storage id
let storage = {};
storage["status"] = "no status";
chrome.storage.local.set({storageid: storage},function(){

});

But even in that instance the key is still "storageid" not necessarily the value held in the variable storageid. It's a bit tricky to explain the problem because of my little understanding of how chrome's local storage works. So any help would be greatly appreciated.

Irelia
  • 3,407
  • 2
  • 10
  • 31
  • 1
    I'm not familiar with Chrome extensions but can you try changing `chrome.storage.local.set({storageid: storage} ...` to `chrome.storage.local.set({[storageid]: storage} ...` – Austin Ezell May 29 '19 at 20:33
  • Oh @AustinEzell Thank you! That seemed to do the trick! I feel so dumb sometimes. Can you write that as an answer instead of a comment? – Irelia May 29 '19 at 20:36
  • Cool, I'll write up a quick answer on why this is the case. – Austin Ezell May 29 '19 at 20:39

1 Answers1

2

When you form your JS object, you are writing {storageid: storage}. This storageid here is still just the string "storageid". What you are looking for is the value of the variable itself. {[storageid]: storage} interprets the variable storageid into the its value.

Not that it matters when building a Chrome plugin, but I figure it is worth pointing out that this is a more modern syntax of JS and would not work in IE. There, the solution would still have to be.

var storageObj = {}
storageObj[storageid] = storage
Austin Ezell
  • 753
  • 4
  • 12