coconut coconut - 1 month ago 9
Javascript Question

Using idb instead of localStorage

I'm following the Progressive Web App lab from Google and it says that it's using localStorage for simplicity but that we should change it to idb.

Basically, we want to store a list of cities to display their weather information.

I tried using plain idb following the info here but I think I'm too new to this and I couldn't get any of this. Am I supposed to do:

const dbPromise = idb.open('keyval-store', 1, upgradeDB => {
upgradeDB.createObjectStore('keyval');
});


and would keyval be the name of my variable where I would use keyval.get() or keyval.set() to get and store values?

I decided to move on to the simpler idbKeyval, I'm doing:

app.saveSelectedCities = function() {
var selectedCities = JSON.stringify(app.selectedCities);
idbKeyval.set(selectedCities);
};


instead of the localStorage example:

app.saveSelectedCities = function() {
var selectedCities = JSON.stringify(app.selectedCities);
localStorage.selectedCities = selectedCities;
};


and

app.selectedCities = idbKeyval.keys().then(keys => console.log(keys)).catch(err => console.log('It failed!', err));


instead of the localStorage example:

app.selectedCities = localStorage.selectedCities;


But my app is not loading any data, and in the developer tools console, I get:

app.js:314 Uncaught ReferenceError: idbKeyval is not defined(…)


I'm sure I'm missing something trivial but these are my first steps with javascript and the likes, so please, any help with any of the points touched here would be greatly appreciated!

Answer

Given the error you're seeing, it looks like you've forgotten to include the idb-keyval library.