Async storage not working to set or get on React Native

Im trying to make the user authentication using async storage to decide which screen will be rendered so when i get the data from the async storage returns to me undefined can someone help me?

My get code:

var login;
AsyncStorage.getItem("login").then((value) => {
      login = value;
}).done();
alert(login);

My set code:

const insert_user = (username) => {
  AsyncStorage.setItem("login", username);
  Toast.show({
    supportedOrientations: ['portrait', 'landscape'],
    text: `User registered with success`,
    position: 'bottom',
    buttonText: 'Dismiss'
  });
}

Upvotes: 11

Views: 24264

Answers (5)

Jorge Santos Neill
Jorge Santos Neill

Reputation: 1785

The complete to use AsyncStorage with async and await is the following

import { getItem as localStorageGetItem, setItem as localStorageSetItem } from 'services/localStorage';
async loginHandler (){
     localStorageSetItem(ACCESS_TOKEN, response.accessToken);
     var token = await localStorageGetItem(ACCESS_TOKEN);
}

localStorage.js file

import AsyncStorage from '@react-native-community/async-storage';

export const getItem = async(item) => {
    try {
        const value = await AsyncStorage.getItem(item);
        return JSON.parse(value);
    } catch (error) {
        return null;
    }
};

export const setItem = async(item,value)=>{
    try {
        await AsyncStorage.setItem(item, JSON.stringify(value));
    } catch (error) {
        console.log("SetItem error ",error)
        return null;
    }
}

Upvotes: 2

James Siva
James Siva

Reputation: 1323

import { AsyncStorage } from 'react-native';

AsyncStorage.setItem('mobileNumber', phoneNumber.number);

AsyncStorage.getItem('mobileNumber', (error, result) => {
  this.setState({
    loginMobileNo: result,
  });

Upvotes: 2

Gaurav Rami
Gaurav Rami

Reputation: 1287

Using "react-native": "0.56.0" :-

Create a file named "Pref.js" with below contents. (Pref.js is like a global file for set and get data using AsyncStorage so that you can use in any .js file).

//---- Pref.js ---->
import { AsyncStorage, Alert } from "react-native"

export const kUserName = 'user_name';
export const kUserID = 'user_id';


export const setData = async (strKey, item) => {
    let value = JSON.stringify(item)
    if (value) {
        AsyncStorage.setItem(strKey, value);
    }
}

export const getData = (strKey, callback = (response1) => { }) => {
    AsyncStorage.getItem(strKey).then((value) => {
        callback(value)
    });
}

--------- Using above file in your "index.js" file ---------> (import Pref.js file with correct path)

import * as Pref from '../../Pref/Pref'   //IMPORTANT: set your file path.

onLoginClick = () => {

    // Set data in AsyncStorage using "Pref.js" file. "Pref.kUserName" is from Pref.js file:
    Pref.setData(Pref.kUserName, 'Hello World')

    // Get data from AsyncStorage using "Pref.js" file.
    Pref.getData(Pref.kUserName, (value) => {
        if (value) {
            Alert.alert(`Welcome ${value}`)
            //this.props.navigation.push('Home')
        }
    });
}

Upvotes: 0

Pankaj Bhardwaj
Pankaj Bhardwaj

Reputation: 2131

At my end AsyncStorage.getItem('foo') works when I used StrigyFy at the time of set item.

var myStr = JSON.stringify(yourData);

To Set item with key

AsyncStorage.setItem('key', myStr);

To Get item

var value = AsyncStorage.getItem('key');

Upvotes: 0

Sharlon M. Balbalosa
Sharlon M. Balbalosa

Reputation: 1309

alert(login); will always be undefined because AsyncStorage.getItem is asynchronous in nature meaning alert(login) is called first before you receive the value from AsyncStorage.getItem

AsyncStorage.getItem("login").then((value) => {
      alert(value); // you will need use the alert in here because this is the point in the execution which you receive the value from getItem.
    // you could do your authentication and routing logic here but I suggest that you place them in another function and just pass the function as seen in the example below.
});

// a function that receives value
const receiveLoginDetails = (value) => {
    alert(value);
}
// pass the function that receives the login details;
AsyncStorage.getItem("login").then(receiveLoginDetails);

Further reference

Upvotes: 13

Related Questions