0

This question is actually more about javascript. I've just started learning it and I'm a Java developer, so some things in JS seem unclear to me.

I'm working on a chrome extension and trying to call chrome's storage API like this

const key = 'myKey';
const value = { name: 'my value' };

chrome.storage.local.set({key: value}, () => {
  console.log('Stored name: ' + value.name);
});

I can see that const key is greyed out, so in the curly braces {key: value} the constant variable is not the one being used. I also tried to change it to {blabla: value} and blabla is still shown as an existing variable in the IDE. It doesn't go to any declaration when I try to, but still it's a weird behaviour. I'm not sure which JS concept I should research about in order to understand this. Thanks!

UPD: now it became even weirder. I tried out some things and got it working for my specific scenario, but how it works is still a mystery to me. So, when saving the key-value pair the following way

    chrome.storage.sync.set({testKey: value}, function() {
        console.log('Value is set to ' + value);
    });

and reading it like

chrome.storage.sync.get(['testKey'], function (result) {
    console.log('Value currently is ' + result.testKey);
});

Then I'm getting the (un)expected output in console.

Vahancho22
  • 23
  • 3
  • Think of JS objects like `Map`. Syntax like `{key: value}` is the equivalent of `map.put("key", value)`. If you want a dynamic key, use `{[key]: value}` which is the equivalent of `map.put(key, value)`. See [Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) – Phil Sep 02 '22 at 00:45
  • Looking at [the docs](https://developer.chrome.com/docs/extensions/reference/storage/#type-StorageArea-set-items) for `sync.set()`, I don't think you can store objects, just primitives and arrays... _"Primitive values such as numbers will serialize as expected. Values with a `typeof` `"object"` and `"function"` will typically serialize to `{}`, with the exception of `Array` (serializes as expected), `Date`, and `Regex` (serialize using their `String` representation)."_ – Phil Sep 02 '22 at 00:53
  • Finally, I think `sync.set()` is asynchronous. You may need to move your `get()` code into the callback function – Phil Sep 02 '22 at 00:57
  • Check out this question for how to set the value for key from a var: https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable – justinw Sep 02 '22 at 01:43

0 Answers0