Capacitor 3 - When to use Storage.migrate()

I am upgrading to Capacitor 3 and I’m using the Storage API. My app already had some data stored locally but after upgrading I find the data is not able to be read. I can see the data in Chrome Devtools.

So I guess I need to use Storage.migrate() ?

What I’m not sure about is where to use it and how to use it just the once… or do I just keep calling it forevermore (doesn’t seem right)?

Writing that out now gets me thinking that it’ll be tied in with my app versions, is that the normal approach?

1 Like

Did you ever figure this out? I was wondering the same thing myself.

I already had an internal database version in the store so I’m going to bump that and have a hardcoded check for the older version.

I tried using getInfo() from Capacitor’s App API but it is not ‘Not implemented on web’. So, if you’re developing an app but using a browser for development this won’t work. It is possible appVersion might work in the browser but I haven’t tried it.

It might be that you don’t need to add a check at all, and migrate() does the check for you because it obviously knows the format of the data, but no-one from the ionic or capacitor teams responded to my query, and the docs don’t say either, so who knows!?

I will try it out this week. Let me know how you get on.

This clearly isn’t going to work because the db version is stored… using storage from Capacitor v2!! :wink:
I could use localstorage.getItem(’_cap_myKey’) in the browser to read the v2 data but I don’t know if that works in Android or iOS.

So I’ve had a look a the code in node_modules/@capacitor/storage/dist/plugin.js and it seems as though the prefix has changed between versions. The code checks for any keys stored using the old prefix (_cap_), and then, if old keys were found, writes out new keys with the new/current prefix.

As that is all it seems to do it’s probably quite safe to include migrate() in your app on startup forevermore.

I hope that helps.

While I haven’t tried it myself, there’s the migrate function. Usually, you would call migrate once upon app startup. Then going forward, use the Storage API as you currently are (since I believe the API didn’t change between v2 and v3).

You could leave that code in place forever, or remove it in a future app version once you’re comfortable enough that users have all been updated.