COMisHARD
COMisHARD

Reputation: 925

Querying for local storage entry without throwing errors

Working on a chrome extension. I am using the following to save some data to my local storage:

chrome.storage.local.set({ [variablyNamedEntry]: someObjectToBeSaved });

Elsewhere in my code I want to query if the entry exists and if it does, I will want to local some variable "myVar" with the object.

If the entry exists, this code works to achieve my goals:

chrome.storage.local.get(null, function(result){
    myVar = result[variablyNamedEntry];
}

But if no entry exists for "variablyNamedEntry" it throws an error. I could manage this error with a try/catch sequence. But that can't be the best approach, given that I know that it will not find the entry a very large percentage of the time.

How can I achieve my goal?

Update:

I tried using:

chrome.storage.local.get([variablyNamedEntry], function(result){
    if (result != undefined)
        myVar = result[variablyNamedEntry];
}

But I still get the following error if the entry does not exist:

 extensions::uncaught_exception_handler:8 Error in response to storage.get: TypeError: Cannot read property 'someProperty' of undefined

Upvotes: 0

Views: 55

Answers (1)

Haibara Ai
Haibara Ai

Reputation: 10897

Please be aware the items parameter for the callback of chrome.storage.local.get is always an object and would never be undefined.

Assuming you have a key-value in which key is 'Sample-Key', you could use the following code

chrome.storage.local.get(null, function(result){
    if(typeof result['Sample-Key'] !== 'undefined') {
        console.log(result['Sample-Key']);
    }
});

Or

chrome.storage.local.get('Sample-Key', function(result){
    if(typeof result['Sample-Key'] !== 'undefined') {
        console.log(result['Sample-Key']);
    }
});

Upvotes: 2

Related Questions