sabih siddiqui
sabih siddiqui

Reputation: 133

how can i save object in mobille storage using react native

I am building an application in which I want to save user data. and user able to see that data later. I am using AsyncStorage.. i want to store multiple values in one key. I used AsyncStorage.setItem.. here is my code..

var obj ={
       name : "sabih",
       color : "blue"
}
AsyncStorage.setItem('myKey', JSON.stringify(obj))
     .then(() => {
         console.log('data saved')
})

but when i get data with AsyncStorage.getItem. it gives me like this

{"name":"sabih" , "color" : "blue"}

Code here

AsyncStorage.getItem("myKey").then((data) => {
   var userData = JSON.parse(data)
      console.log(userData, 'Get Values')
}).done();

How can i set name's and color's value in state. or how can i render these values in my react native application..

Thanks in advance. and please attach a snap of solution if possible..

Upvotes: 1

Views: 1660

Answers (1)

Akshay Rao
Akshay Rao

Reputation: 3544

Create a function inside your file and call that function passing your asyncstrorage value as parameter as below :-

_renderDetail=(item)=>{
   this.setState({user:item});
}

and inside your asyncStorage code edit as :-

AsyncStorage.getItem("myKey").then((data) => {
   var userData = JSON.parse(data);
   console.log(userData, 'Get Values');
   this._renderDetail(userData);
}).done();

and then you can use this state variables inside your render function as :-

<Text>{this.state.user.name}</Text>
<Text>{this.state.user.color}</Text>

Upvotes: 2

Related Questions