React-native sync storage solution - react-native

In native iOS code, I could use the NSUserDefaults to store and fetch data, which are sync operations. In react-native the offer is to use AsyncStorage, but I need a solution for sync storing, like NSUserDefaults.
I'm gonna use the result of data fetching to determine which screen to show, but since it's async I always get undefined when trying to fetch the persisted data.

after calling
AsyncStorage.getItem('#MySuperStore:key');
react-native will call native function dependent on your platform in other thread
then it will return a promise to resolve it
,so if call like this
let value = AsyncStorage.getItem('#MySuperStore:key');
value ++;
your value is not valid cause it data will be available later
the correct way to do is :
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
if (value !== null){
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
other way of doing this is
try {
AsyncStorage.getItem('#MySuperStore:key',(value )=>{
if (value !== null){
// We have data!!
console.log(value);
}});
} catch (error) {
// Error retrieving data
}

you could make it asynchronous for example
getData = async () => {
const value = await AsyncStorage.getItem('Yourkey');
this.setState({key: value})
}

Related

AsyncStorage functions just producing garbage in react native

So I implemented this code in a file from the react native docs.
class Storage {
//store data in 'key'
store = async (key, data) => {
try {
await AsyncStorage.setItem(key, data);
} catch (error) {
// Error saving data
console.log(error.message);
}
};
retrieve = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
console.log(error.message);
}
};
}
And this in other I want to use to actually store and retrieve the variables:
strg.store('test', 'testing');
testing = strg.retrieve('test');
I kept getting an error but then looking it up here I figured out my storage output was an object and not a string as I expected. So I used JSON.stringify(***) and this gibberish came out instead of a "testing".
{"_40":0, "_65":0, "_55":null,"_72":null}
edit: I figure out how to use the console to debug and I found out the 'testing' was inside the promise object that comes out of my function. I read a little about async functions and now I want to know how do I extract the values from the promises?
This happened because you are using AsyncStorage - an asynchronous storage system. You have to wait until it done retrieve data from storage to get the proper data.
I think there are two correct ways to get data from your implementation:
Use async with your container function name & await with your function called
async function getData() {
....
let data = await strg.retrieve('test');
console.log("data", data);
}
or simple use .then():
strg.retrieve('test').then((data) => {
console.log("data", data);
// Handle retrieved data
});
Hope that help. :)
This is how i did it and it works like a charm
import { AsyncStorage } from 'react-native';
module.exports = {
retrieve: async (value) => {
try {
let data = await AsyncStorage.getItem(value);
return data;
} catch (err) {
return err;
}
},
store: async (key, value) => {
try {
// stringify the value since value can only be string.
if (typeof (value) === 'object')
value = JSON.stringify(value)
return await AsyncStorage.setItem(key, value);
} catch (err) {
console.log(err)
return err;
}
}
}
Your store and retrieve functions are asyn so you have to use await until the actual task is complete.
So the code should be like below.
await strg.store('test', 'testing');
const testing = await strg.retrieve('test');
The garbage value is a promise so it will be something like the object you got.
If you return value like this you will retrieve it from outside.
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// We have data!!
console.log(value);
return value;
}

Can I use a function with async await inside ComponentDidMount in React Native?

I am using AsyncStorage.getItem in React Native.
As soon as the Application loads, I want to get the saved data in the device memory using AsyncStorage.getItem. I thought of using ComponentDidMount(). So as soon as the components are loaded, I want to run the AsyncStorage.getItem automatically and save the data to the array DATA. This way the user will not push any button to start rendering what is saved on the memory of the device.
I used the code below, but I do not see any console.log activity. But the console.log works on my other pages on same program here. It seems the ComponentDidMount() did not get executed.
Thanks!
componentDidMount(){
async () => {
try {
const HomeData = await AsyncStorage.getItem('#MyApp_Homekey')
return HomeData
} catch (e) {
console.log('There was error.')
}
if(!HomeData){
console.log('There are no Dimmer Light saved in the memory.')
}
else {
console.log('There is value in data after getItem.')
this.setState(DATA = HomeData)
}
}
As metioned in comment you should use async for componentDidMount as:-
componentDidMount = async () => {
const HomeData = await AsyncStorage.getItem('#MyApp_Homekey')
if(!HomeData){
console.log('There are no Dimmer Light saved in the memory.')
}
else {
console.log('There is value in data after getItem.')
this.setState(DATA = HomeData)
}
}

local storage variables are reinitialized when i quit the application

what i want to do is to show a dialog box when i open the app,but i want to condition this display to a variable stored in my app local storage.
this variable get initialized when i click on a button.
i'll explain my case:
when i click on my button i do call this function which store data in my local storage as follow:
storeDate = async () => {
try{
await AsyncStorage.setItem('#key',true)
}catch(e){
alert("an error has occured when s")
}
}
and in my componentDidMount, according to my #key variable i do display my dialog box or not, here is my code for doing that:
componentDidMount(){
// this alert is used to check my #key variable value
alert(this.getData());
if (this.getData() == true){
this.setState({
dialogVisible2:true
});
}
}
here is my getData function:
getData = async () =>{
try{
const value = await AsyncStorage.getItem('#key')
if (value !== null){
return value;
}
return "undefined";
}catch(e){
alert("an error has occured when retrieving data")
}
}
when i close the app and re-open it the alert returns me the following [ object Objecct].
can anyone tell me where i'm wrong.
The componentDidMount function runs first before data is obtained from Asyncstorage, so the value is imported.
So you can configure componentDidMount as a asynchronous system.
async componentDidMount(){
getdata = await this.getData()
alert(getdata);
if (getdata === true){
this.setState({
dialogVisible2:true
});
}
}

React Native AsyncStorage: Accessing Value from Promise Object

When I use AsyncStorage.getItem() to retrieve the value (an email address) of a specified key, it returns a Promise object as indicated in the documentation. The value appears in object like so:
{
_45: 0
_54: null
_65: "testuser#test.com"
_81: 1
}
Can I reliably access this value by calling obj._65 or is there another way to accomplish this?
AsyncStorage return a promise. you can use .then for get value
exemple:
AsyncStorage.getItem('key').then((keyValue) => {
console.log(keyValue) //Display key value
}, (error) => {
console.log(error) //Display error
});
Looking at the docs you should be able to do this reliably to retrieve data from your async storage object.:
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
if (value !== null){
// We have data!!
console.log(value._65);
}
} catch (error) {
// Error retrieving data
}
you must use this within a function that is async however or you will get a runtime exception.

Unable to return token from AsyncStorage in React Native

I am using React Native's AsyncStorage to store an authorization token, which will be returned when needed to use for new http requests. While I can successfully store it and console log it, I am having some trouble returning the value. I want to call it in another window, in the fashion of
var x= LocalDb.getAcessToken();
console.log(x);
However it won,t work.
LocalDb.getAccessToken();
This on the other hand, works when getAcessToken() has console.log in it
exports.storeToken=function(token){
AsyncStorage.setItem('access_token', token);
}
^^^^This function successfully saves the token
exports.getAccessToken=function(){
AsyncStorage.getItem('access_token')
.then((value) => {
if(value) {
console.log(value);
**//I want to return the value here, to use in another function**
}
})
.done();
}
I can not return the value when I use the return(value) . How can I return a value from the promise?
You need to return the getAccessToken function with the promise call. I would also return the promise with the value... like this.
exports.getAccessToken=function(){
return AsyncStorage.getItem('access_token')
.then((value) => {
if(value) {
console.log(value);
return value;
}
})
}