How to store array of objects using AsyncStorage in react native

Viewed 368

I am trying to store an array of objects, where each object has a string label and corresponding data of type array like:

arrayOfCategory=[
 {label: "A", data: Array(36)}
 {label: "B", data: Array(20)}
 {label: "C", data: Array(20)}
 .....
];

ScreenShoot of the array:

ScreenShoot of the inner array:

When I tried to store it like :

AsyncStorage.setItem("arrayOfCategoryStroage", JSON.stringify(arrayOfCategory));

I have an empty array if I get the item from the storage.

   AsyncStorage.getItem('arrayOfCategoryStroage').then((value) => {
       console.log(JSON.parse(value))
    });
2 Answers

There might be Issue, the way you are getting Item, and Make sure your Aysnc Storage is not getting cleared somewhere, in that case all the data will be lost.

you can set the Item by

 AsyncStorage.getItem('arrayOfCategoryStroage',JSON.stringify(data))

then fetch it like this and also check if there is any error.

 AsyncStorage.getItem('arrayOfCategoryStroage', (err, result) => {
            if (result) {
             const data= JSON.Parse(result);
            }
        }).catch(() => {
        });

I tried to store each item label separately like:

AsyncStorage.setItem(item.label, JSON.stringify(data));

Then i get each of them and push into array:

data1.forEach((item, i) => {
  AsyncStorage.getItem(item.label).then((value) => {
     if(value!=null)
     {
      arrayOfAll.push({label:item.label,data:JSON.parse(value)})
    
     }
})
});

Where data1 is an array of labels:

const data1=[ {label: "Homepage"},
{label: "Politik"},
{label: "Lokal"},
]

I think the problem is coming from the large size of inner array.

I tried it with small array and it works fine like:

   const someArray=[
     {label: "A", data: [{id:"1", title:"title1"},{id:"2", title:"title2"}]},
     {label: "B", data: [{id:"1", title:"title1"},{id:"2", title:"title2"}]},
     {label: "C", data: [{id:"1", title:"title1"},{id:"2", title:"title2"}]},
    ]; 
Related