Search code examples
react-nativeasyncstorage

Two instances of AsyncStorage in React Native?


Can I have two instances of AsynStorage? I get that when you set an item you can for example stringify an array and have something like:

AsyncStorage.setItem( 'names' , '[John, Carl, Sam]' );

Because I understood that you cant save an Object or an Array as a value in AsyncStorage. So is there a way to have more than one instance to have something like this:

Instance 1 AsyncStorage:
-["a","aaa"]
-["b","bbb"]
-["c","ccc"]

Instance 2 AsyncStorage:
-["d","ddd"]
-["e","eee"]
-["f","fff"]

And call for example Instance2AsyncStorage.getItem("d") and if I want something from Instance 1 I do Instance1AsyncStorage.getItem("a")?


Solution

  • You should convert it to string and save it and then when you want to use it you can parse it. For example:

    const arr = ["a", "b"];
    // First you should convert it to string and then save it
    await AsyncStorage.setItem('names' , JSON.stringify(arr));
    
    // Then you can do this for using it:
    const response = await AsyncStorage.getItem('names');
    const result = JSON.parse(response);