React-Native: save user preferences

floriantaut picture floriantaut · Aug 9, 2018 · Viewed 10.2k times · Source

Native developers,

I really searched a lot but couldn't find anything that fits my needs.

I am new to react native and have a question. I wonder how I can save user preferences of my app.

For example, I am displaying a dismissible badge on my screen -> user dismisses it -> how do I save this decision so the badge won't appear on every start again?

I thought about writing a .json file where all preferences are defined and read it on every start.

Is this a common way to realize it or is there any other solution.

Thank you very much

Answer

I Putu Yoga Permana picture I Putu Yoga Permana · Aug 10, 2018

There are so many options out there, but the most common you can use React Native, built-in AsyncStorage.

Sample Code

import { AsyncStorage } from "react-native";
const storeKey = 'myPreference';
storeData = async () => {
  try {
    await AsyncStorage.setItem(storeKey, 'I like to save it.');
  } catch (error) {
    // Error saving data
  }
}

retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem(storeKey);
    if (value !== null) {
      // We have data!!
      console.log(value);
    }
   } catch (error) {
     // Error retrieving data
   }
}

read more at https://facebook.github.io/react-native/docs/asyncstorage.html

Or you could reconsider 3rd party library like:

https://github.com/kevinresol/react-native-default-preference

https://github.com/mCodex/react-native-sensitive-info