Reputation: 12574
I am trying to check if the entry exists in the AsycStore and if it doesn't exist then, I create an object and set it. And there is a return statement that returns the dataobject.
Here is the pseudocode-
AsyncStorage.getItem("dataobject").then((do) => {
if(do == undefined)
{
console.log("initializing obj + setting data");
var dobj = "data object";
dobj.isdirty = true;
AsyncStorage.setItem("dataobject",dobj);
}
return AsyncStorage.getItem("dataobject");
}).done();
},
I am getting an error in console -
W/ReactNativeJS: 'Error: Attempted to assign to readonly property.\n stack: \n <unknown>
index.android.bun…:53047\n tryCallOne
index.android.bun…:5094\n <unknown>
index.android.bun…:5160\n <unknown>
index.android.bun…:3399\n callTimer
index.android.bun…:2954\n callImmediates
index.android.bun…:3003\n <unknown>
index.android.bun…:2523\n guard
index.android.bun…:2452\n __callImmediates
index.android.bun…:2523\n <unknown>
index.android.bun…:2503\n guard
index.android.bun…:2452\n invokeCallbackAndReturnFlushedQueue index.android.bun…:2501\n URL: http://localhost:8081/index.android.bundle?platform=android&dev=true\n line: 53047\n message: Attempted to assign to readonly property.'
I am not really sure what is the readonly property I am trying to assign. The line number that is being warned is this line - "dobj.isdirty = true";
Should I not add a property to an object? How do I solve this problem? What's the right way of doing it?
Screenshot-
Upvotes: 5
Views: 31347
Reputation: 2309
Is dobj a string or an object?
var dobj = "data object";
dobj.isdirty = true;
In the second line, dobj.isdirty is undefined and you're trying to set that ("undefined" is a readonly property of JS).
Now if you're trying to do
var dobj = {};
dobj.isdirty = true;
Then instead you should do
var dobj = {};
dobj['isdirty'] = true;
OR
var dobj = {isdirty: true};
Upvotes: -3
Reputation: 53691
You can probably accomplish this by using the .catch, which should throw if there is not a value there. Something like:
AsyncStorage.getItem("dataobject")
.then((do) => {
this.setState({
myData: do.toJSON();
})
})
.catch(() => {
console.log("initializing obj + setting data");
var dobj = {};
dobj.isdirty = true;
AsyncStorage.setItem("dataobject",JSON.stringify(dobj));
});
Upvotes: 5