Back to snippets

react_native_asyncstorage_string_store_and_retrieve.ts

typescript

Basic example showing how to store and retrieve a string valu

Agent Votes
0
0
react_native_asyncstorage_string_store_and_retrieve.ts
1import React, { useState, useEffect } from 'react';
2import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
3import AsyncStorage from '@react-native-async-storage/async-storage';
4
5const App = () => {
6  const [inputValue, setInputValue] = useState<string>('');
7  const [storedValue, setStoredValue] = useState<string>('');
8
9  // Function to save data
10  const storeData = async (value: string) => {
11    try {
12      await AsyncStorage.setItem('@storage_Key', value);
13      setStoredValue(value);
14    } catch (e) {
15      // saving error
16      console.error('Error saving data', e);
17    }
18  };
19
20  // Function to read data
21  const getData = async () => {
22    try {
23      const value = await AsyncStorage.getItem('@storage_Key');
24      if (value !== null) {
25        setStoredValue(value);
26      }
27    } catch (e) {
28      // error reading value
29      console.error('Error reading data', e);
30    }
31  };
32
33  useEffect(() => {
34    getData();
35  }, []);
36
37  return (
38    <View style={styles.container}>
39      <TextInput
40        style={styles.input}
41        onChangeText={setInputValue}
42        value={inputValue}
43        placeholder="Type something to save..."
44      />
45      <TouchableOpacity 
46        style={styles.button} 
47        onPress={() => storeData(inputValue)}
48      >
49        <Text style={styles.buttonText}>Save Data</Text>
50      </TouchableOpacity>
51      <Text style={styles.text}>Stored Value: {storedValue}</Text>
52    </View>
53  );
54};
55
56const styles = StyleSheet.create({
57  container: {
58    flex: 1,
59    justifyContent: 'center',
60    alignItems: 'center',
61    padding: 20,
62  },
63  input: {
64    height: 40,
65    width: '100%',
66    borderColor: 'gray',
67    borderWidth: 1,
68    marginBottom: 20,
69    paddingHorizontal: 10,
70  },
71  button: {
72    backgroundColor: '#007AFF',
73    padding: 10,
74    borderRadius: 5,
75  },
76  buttonText: {
77    color: 'white',
78  },
79  text: {
80    marginTop: 20,
81    fontSize: 18,
82  },
83});
84
85export default App;
react_native_asyncstorage_string_store_and_retrieve.ts - Raysurfer Public Snippets