TypeError: val.set is not a function (JS Map())

Viewed 250

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"
]
1 Answers

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);
});
Related