Install AsyncStorage

You need to install the @react-native-async-storage/async-storage package. Run the following command in your project directory:

bashCopy codenpm install @react-native-async-storage/async-storage

Step 2: Update App.js

Replace the existing code in App.js with the following code:

javascriptCopy codeimport React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, Button, TouchableOpacity, Alert } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const App = () => {
  const [items, setItems] = useState([]);
  const [textInput, setTextInput] = useState('');

  // Load items from AsyncStorage on app start
  useEffect(() => {
    const loadItems = async () => {
      try {
        const storedItems = await AsyncStorage.getItem('items');
        if (storedItems) {
          setItems(JSON.parse(storedItems));
        }
      } catch (error) {
        console.error(error);
      }
    };
    loadItems();
  }, []);

  // Save items to AsyncStorage whenever they change
  useEffect(() => {
    const saveItems = async () => {
      try {
        await AsyncStorage.setItem('items', JSON.stringify(items));
      } catch (error) {
        console.error(error);
      }
    };
    saveItems();
  }, [items]);

  const addItem = () => {
    if (textInput.trim()) {
      setItems([...items, { key: textInput }]);
      setTextInput('');
    }
  };

  const deleteItem = (itemToDelete) => {
    setItems(items.filter(item => item.key !== itemToDelete));
  };

  const confirmDelete = (item) => {
    Alert.alert(
      'Delete Item',
      `Are you sure you want to delete "${item.key}"?`,
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'OK', onPress: () => deleteItem(item.key) },
      ],
      { cancelable: true }
    );
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>My Item List</Text>
      <TextInput
        style={styles.input}
        placeholder="Add a new item"
        value={textInput}
        onChangeText={setTextInput}
      />
      <Button title="Add Item" onPress={addItem} />
      <FlatList
        data={items}
        renderItem={({ item }) => (
          <TouchableOpacity onLongPress={() => confirmDelete(item)}>
            <Text style={styles.item}>{item.key}</Text>
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.key}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
  },
  item: {
    padding: 10,
    fontSize: 18,
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
  },
});

export default App;

Comments

Leave a Reply

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