Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncStorage.getItem returns undefined : React Native

Codeflow is-

I am checking if an entry called listobject exists in the AsyncStorage.

  1. If it doesn't exist, then, I create an object, add few attributes and set the store. I get the store to obj as I have to compare in the next if condition.

  2. If the listobject entry already exists(2nd time), then, it directly comes to the 2nd block, and compares. (The reason I get values to obj in 1st step is because I can have a common obj.data.isdirty condition.

Here is my code-

AsyncStorage.getItem('listobject').then((obj) => {
    if(obj == undefined)
    {
        var obj1 ={};
        obj1.data ={};
        obj1.data.isdirty = true;
        console.log("obj1 = "+ JSON.stringify(obj1));
        AsyncStorage.setItem('listobject',obj1);
        obj = AsyncStorage.getItem('listobject');
        console.log("obj = "+ JSON.stringify(obj));
    }
    if(obj.data.isdirty)
    {
        obj.data.isdirty = false;
        AsyncStorage.setItem('listobject',JSON.stringify(obj));
        return AsyncStorage.getItem('listobject');
    }
}).done();

I have 2 questions which are the outcome of the same issue-

  1. Logs. I am setting obj1 and getting the same value for obj (so that I can compare the next if condition). Why am I not able to get the same value that I have set?

12-03 00:27:56.281 32598-487/com.abc D/ReactNativeJS: 'obj1 = {"data":{"isdirty":true}}'

12-03 00:27:56.286 32598-487/com.abc D/ReactNativeJS: 'obj = {"_37":0,"_12":null,"_59":[]}'

  1. This is the end result of the above logs. I am getting that list.data.isdirty is undefined. I guess that because the JSON format I am accessing does not exist in obj i.e., obj.data.isdirty doesn't exist. So, how do I overcome this?

undefined is not an object (evaluating 'list.data.isdirty');

Please tell me what am I doing wrong?

like image 670
bozzmob Avatar asked Sep 27 '22 01:09

bozzmob


1 Answers

I actually copied the object from one to another. It worked.

AsyncStorage.getItem('listobject').then((obj) => {
    if(obj == undefined)
    {
        var obj1 ={};
        obj1.data ={};
        obj1.data.isdirty = true;
        console.log("obj1 = "+ JSON.stringify(obj1));
        AsyncStorage.setItem('listobject',obj1);
        obj = obj1; //THIS IS WHAT I DID!
        console.log("obj = "+ JSON.stringify(obj));
    }
    if(obj.data.isdirty)
    {
        obj.data.isdirty = false;
        AsyncStorage.setItem('listobject',JSON.stringify(obj));
        return AsyncStorage.getItem('listobject');
    }
}).done();
like image 125
bozzmob Avatar answered Sep 29 '22 00:09

bozzmob