Handling database upgrades
As it may be already apparent, IndexedDB databases are tagged with a version number. Whenever the app requests a database version that is newer than the one the user actually has, onupgradeneeded
will be called so that the app has a chance to modify the database.
Note
The snippets in this section are located at snippets/07/ex3-upgrade-database/*
in the code package of this book. When using the interactive snippet playground, select 7: IndexedDB and examples 3a to 3b
Thankfully, onupgradeneeded
is provided with the old version number of the database and the desired version number of the database, otherwise we'd have difficulty deciding what needed to be changed. With this information, we can upgrade our database pretty simply. First, let's modify our openDatabase
function slightly to the following:
// Example Snippet 3a function openDatabase({name, version, onopen, onerror, onupgrade}) { let req = indexedDB.open(name, version); req.onerror = function(evt) ...