How to store value in LocalStorage in React Native

Viewed 108691

I am new at React Native and I am creating an app in which I need to store values in local storage like SharedPref in Android .

Ex: If user loggedIn then control should go to Dashboard otherwise login screen should appear

Thank You in advance

9 Answers

There are several options to do such thing.

For most basic things you can use AsyncStorage from react-native, but there are other options, like Realm and SQLite that are libraries to store data on device.

If you are using Redux, you can also use redux-persist.

EDIT

As @honor said, you should use react-native-community/react-native-async-storage instead of the older AsyncStorage referenced here (deprecated)

you can use sync storage that is easier to use than async storage:

import SyncStorage from 'sync-storage';

...

SyncStorage.set('foo', 'bar');

const result = SyncStorage.get('foo');
console.log(result); // 'bar'

AsyncStorage is best option to store some data you can use like below example:

AsyncStorage.setItem('access_token', responseData.data.access_token);

This is my separate component where you can create a separate function for import any where example:

export const isSignedIn = () => {
  return new Promise((resolve, reject) => {
    AsyncStorage.getItem(USER_KEY)
      .then(res => {
        if (res !== null) {
          resolve(res);
        } else {
          resolve(false);
        }
      })
      .catch(err => reject(err));
  });
};

How to import?

import { isSignedIn, url } from "./Auth";

isSignedIn()
    .then(res => {
      this.changeLoaderStatus();
      if(res){
        res; //this is your token 
      }
    }

You will get the package from below URL:

https://github.com/react-native-async-storage/async-storage

You can't use LocalStorage in React-Native, you can use AsyncStorage instead.

Edit : You can also use a store like redux to handle this.

Don't use AsyncStorage, as there are numerous bugs on Android, and it doesn't seem the RN teams has any interest in fixing it (been several years like that).

In short: don't use AsyncStorage

According to official doc AsyncStorage has been deprecated and now @react-native-community/async-storage will be used
so, follow steps below to use AsyncStorage

yarn add @react-native-community/async-storage

cd ios/ && pod install (For IOS only)

Storing Data

import { AsyncStorage } from 'react-native';

storeData = async () => {
  try {
    await AsyncStorage.setItem('@storage_Key', 'stored value')
  } catch (e) {
    // saving error
  }
}

Reading Data

getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

used AsyncStorage

and perform all your local storage operation like get and set value in react native

Related