0

Whenever I try to get data from chrome.storage, it returns undefined.

chrome.storage.sync.get('courses', function(result) {
      currentCourses = result.courses
      console.log(currentCourses)
      currentCourses.push(coursename)
      chrome.storage.sync.set({courses: currentCourses}, function() {
        alert(`Course "${coursename}" has been added !`)
      });
}
userCourses = async () => {
  await chrome.storage.sync.get('courses', function(result) {
      return(result.courses)
  });
}
courseData = userCourses()
console.log(courseData)

I found an answer here on stack overflow, but it is giving the same error. I am new to JS, and not comfortable with Promises.

I tried the example from the official docs, but it is also giving the same error as below. Can someone help me with a solution, or modify my code ? Error

2 Answers2

0

You use chrome.storage.sync.get() with a completion callback. But notice that the data you retrieve using that .get() method isn't available except within the callback.

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

is the example from the docs. It is the invocation of a function. But that function always and necessarily returns undefined.

Notice that the first parameter to .get() is an array of keys. Your code lacks the array.

The second parameter is the callback function. It looks like this:

function (result) {
   
}

Within the function result.key is the key you requested, and result.value is whatever you stored in the key. You're looking at result.courses, which isn't defined.

Control flow.

  1. The call to .get() completes immediately, always.
  2. At some later time the callback is called.
O. Jones
  • 103,626
  • 17
  • 118
  • 172
0

Wrap the call to storage in a promise and await it:

function getStorageValuePromise(key) {
  return new Promise((resolve) => {
    chrome.storage.sync.get(key, resolve);
  });
}

await getStorageValuePromise('val');