简体   繁体   中英

How to store a Map using AsyncStorage in React-Native?

import * as React from 'react';

let paths = new Map();
  
export function AddPath(path) {
    if (paths.has(path)){
        return
    }
    else{
        paths.set(path, false);
    }

}

export function CompletedPath(path) {
    paths.set(path, true);
}

The above is what my code looks like normally. It functions as expected. I am creating a Map called paths in order to store some important data. It's values are either true or false, while its keys are JSON objects. What I need to do, is to save this Map into asynchronous storage so that it can be retrieved when I reopen the app after closing it. This is my current attempt at modifying my code:

import * as React from 'react';
import AsyncStorage from '@react-native-community/async-storage';

let paths = new Map();

const getData = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('Map')
      let paths = JSON.parse(jsonValue);
    } catch(e) {
      // error reading value  
    }
    alert(paths)
}

const storeData = async (data) => {
    try {
      const jsonValue = JSON.stringify(data)
      await AsyncStorage.setItem('Map', jsonValue)
    } catch (e) {
      // saving error
    }
}

getData();
  
export function AddPath(path) {
    if (paths.has(path)){
        return
    }
    else{
        paths.set(path, false);
        storeData(paths);
    }

}

export function CompletedPath(path) {
    paths.set(path, true);
    storeData(paths);
}

I create the paths Map as usual, and then I call getData() to see if the map already exists in the asyncstorage. Then, wherever I would have updated the map before, I will also update the async storage.

However, I can't get it working. The 'paths' Map always shows as empty when I reopen the app.

Could it be an issue with how I'm storing paths to the asyncstorage because its a Map rather than a JSON object?

Any ideas?

If you do JSON.stringify on the Map , it will be converted to {}.

Convert MAP to Array and use stringify .

 const map = new Map(); map.set('test',true); console.log(JSON.stringify(map)); console.log(JSON.stringify(Array.from(map.entries())));

Stringify

const jsonValue = JSON.stringify(Array.from(data.entries()));

Parse

let paths = new Map(JSON.parse(jsonValue));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM