About Lesson
In this React Native lesson we are going to learn about React Native AsyncStorage, so this is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.
Installation
We need to install this , the built in one is deprecated, if you are using expo you can use this command and for React Native CLI you can change the expo to npm.
1 |
expo install @react-native-async-storage/async-storage |
This is our ReactSync.js component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
import React, {useState, useEffect} from 'react' import { Text, View, TextInput ,Button} from 'react-native' import AsyncStorage from '@react-native-async-storage/async-storage'; function ReactSync() { const [username,setUsername] = useState() const storeData = async () => { try { await AsyncStorage.setItem('MyUsername', username) } catch (e) { // saving error } } const getData = async () => { try { const value = await AsyncStorage.getItem('MyUsername') if(value !== null) { setUsername(value) } } catch(e) { // error reading value } } useEffect(() => { getData() }, []) const removeValue = async () => { try { await AsyncStorage.removeItem('MyUsername') } catch(error) { } finally { setUsername("") } } return ( <View style = {{flex:1, alignItems:"center", paddingTop:50}}> <Text style = {{height:20}}>{username}</Text> <Text style = {{fontSize:25, }}>Write your username here</Text> <TextInput style = {{borderWidth:2, alignSelf:'stretch', height:60, margin:20, paddingHorizontal:10}} placeholder = "Please enter username" onChangeText = {(text) => setUsername(text)} /> <View style ={{flexDirection:"row"}}> <Button title = "Save Username" onPress = {() => storeData()} /> <Button title = "Remove Username" onPress = {() => removeValue()} /> </View> </View> ) } export default ReactSync |
This is our App.js.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import React from 'react'; import ReactSync from './components/ReactSync'; function App() { return ( <ReactSync/> ); } export default App |
Run your application and this is the result, you can write something in the textinput, after that you can save that in the mobile storage.