0

i am trying to save a map to my local storage and for some reason it never saves. i.e. it just saves as {}. The most annoying thing is that I'm sure this worked yesterday!

All help is much appreciated.


export async function getSportsList(){
    let liveOddsApiKey = "blahdedah";
    try{
        let result =  await axios (`${dataSourceURL}${sportDataURL}${liveOddsApiKey}`)

        let sportList = new Map();
        result.data.data.forEach(x=>{
        sportList.set(x.title,x.key);
        });


        console.log("Data Loaded");
        console.log(result);
        console.log(sportList);
        console.log(JSON.stringify(sportList));
       localStorage.setItem('sportsData',JSON.stringify(sportList));
       console.log(localStorage.getItem('sportsData'));
       debugger;



    } catch(error){alert(error);}

}
'''
HarryShotta
  • 347
  • 1
  • 15
  • just to clarify - console.log(result) and console.log(sportList) show expected, but console.log(JSON.stringify(sportList)) shows {} also. – HarryShotta Apr 15 '19 at 23:10
  • For anyone that might be interested, it turns out you have to convert a map to an array before you can json.stringify it! – HarryShotta Apr 15 '19 at 23:29

2 Answers2

0

JSON.stringify on a map results in {}. See https://stackoverflow.com/a/29085474/176868

try this instead...

const sportList = result.data.data.map(x=>({title:x.title, key:x.key}));

..and the rest of your code should work ok.

Sam Sippe
  • 3,160
  • 3
  • 27
  • 40
0

You can't JSON.stringify Map directly. You can store the sportslist as array and store it in the localStorage.

Not sure what data you receive in the result. I have added dummy data in the following fiddle.

See the fiddle

Vinit Divekar
  • 774
  • 10
  • 24