2

I'm having this issue where I'm executing val.set(key, value) and is throwing a type error TypeError: val.set is not a function in the file vendor-es2015.js.

The code (simplified):

import { Storage } from '@ionic/storage';


map = new Map();

this.storage.set('sth', map);

this.storage.get('sth').then((val) => {
    val.set(key, value); //TypeError, returns { } insead of a map.
});

The interesting thing is that this works fine in browsers, but when it's compiled to Android with Capacitor, this error is thrown.

tsconfig.json

"target": "es2015",
"lib": [
  "es2018",
  "dom"
]
jaka_music
  • 354
  • 1
  • 11
  • Did you try debugging to see what the `val` is instead, if it is not the `Map` you expect? – Bergi May 30 '20 at 20:49
  • @Bergi Oh, yes I forgot to mention. Instead of Map object I get returned in browser, I get a classic empty {} object. – jaka_music May 30 '20 at 21:06
  • I’m wondering if maybe Ionic Storage on devices doesn’t support storing Map somehow? Would that even be possibe? – jaka_music May 30 '20 at 21:13
  • Seems likely. I don't know ionic, but have a look at [How do I persist a ES6 Map in localstorage (or elsewhere)?](https://stackoverflow.com/q/28918232/1048572) – Bergi May 30 '20 at 21:18

1 Answers1

2

As the documentation says :

Storage works on Strings only. However, storing JSON blobs is easy: just JSON.stringify the object before calling set, then JSON.parse the value returned from get. See the example below for more details.

Might look like this (updated with help from Bergi):

const mapStr = JSON.stringify(Array.from(map.entries()));
this.storage.set('sth', mapStr);

this.storage.get('sth').then((val) => {
    const theMap = new Map(JSON.parse(val));
    theMap.set(key, value);
});
Sébastien
  • 11,860
  • 11
  • 58
  • 78