Search code examples
typescriptionic2localforage

How to persist a Typescript Map on a Ionic application


So I have some objects within my application with a Map<number,any[]> as one of their attributes. At the moment I am using localForage for the persistence and when the Map is saved it stores it well with ionic serve using an android or windows (browser simulated) but not with an ios one. Also it doesn't work in my android device.

This is a sample of code testing my point:

let myMap: Map<number,any[]> = new Map();
myMap.set(1,['banana','pimento']);
console.log(myMap);
localForage.config({});
localForage.setItem("myMap",myMap)
 .then(()=>localForage.getItem("myMap")
  .then(map => console.log(map))
);

On android and windows (browser simulated) it shows the map just fine, on ios it doesn't. The difference is that the ios one uses a webSQL database and the others use an indexedDB one.

Do I need to serialize it? Is there a better way to store data which fixes this problem?


Solution

  • So I found as a solution to my problem to serialize the Map object with:

    JSON.stringify(Array.from( myMap.entries()));
    

    and deserialize it afterwards with:

    new Map<any,any>(JSON.parse(myMapFromStorage));