How to store/save data in react native

Issue

How to store/save data in react native.Like we use shared-preference in android, is there any solution for react native.I am new to react-nactive.

please add sample example

Solution

You can use React Native AsyncStorage for storing data to local storage of the device.

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

Use this to save data

    AsyncStorage.setItem('key', 'value');

AsyncStorage accepts value as only string, so you may need to use JSON.stringify() before setting the value to AsyncStorage

And to retrieve data use

    AsyncStorage.getItem('key'); 

Example Code :

    const KEY = 'USER_DATA'
    
    let value = { name: yogi }

    AsyncStorage.setItem(KEY, value);

    AsyncStorage.getItem(KEY).then(asyncStorageRes => {
        console.log(JSON.parse(asyncStorageRes))
    });

For sensitive data such as access tokens, payment information, etc. you may wish to use EncryptedStorage

    import EncryptedStorage from 'react-native-encrypted-storage';

It uses a similar API to AsyncStorage so you can use the following to save and retrieve data:

    EncryptedStorage.setItem('key', 'value');
    EncryptedStorage.getItem('key');

There are of course other storage options to choose from too.

Answered By – Hariks

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *