9MenengahPertemuan ke-9

Local Storage & AsyncStorage

Menyimpan data lokal menggunakan AsyncStorage untuk persistensi data.

Topik Pembelajaran

  • AsyncStorage API
  • Save & retrieve data
  • JSON serialization
  • Error handling
  • SQLite alternative
  • Caching strategies
  • Data migration

Referensi & Sumber Daya

Local Storage & AsyncStorage

Tujuan Pembelajaran

  • Menyimpan data secara lokal dengan AsyncStorage
  • Melakukan operasi CRUD data lokal
  • Membuat aplikasi yang bekerja offline

A. Install AsyncStorage

bash
npx expo install @react-native-async-storage/async-storage

B. Operasi Dasar AsyncStorage

Menyimpan Data (setItem)

jsx
import AsyncStorage from '@react-native-async-storage/async-storage'; const saveData = async () => { try { const data = { name: 'John', age: 30 }; await AsyncStorage.setItem('user', JSON.stringify(data)); console.log('Data tersimpan!'); } catch (error) { console.error('Gagal simpan:', error); } };

Mengambil Data (getItem)

jsx
const getData = async () => { try { const data = await AsyncStorage.getItem('user'); if (data) { const user = JSON.parse(data); console.log('Data:', user); } } catch (error) { console.error('Gagal ambil data:', error); } };

Menghapus Data

jsx
await AsyncStorage.removeItem('user'); // Hapus satu item await AsyncStorage.clear(); // Hapus semua

C. Praktik: Aplikasi Catatan (Notes App)

Buat file App.js dengan kode berikut:

jsx
import { useState, useEffect } from 'react'; import { View, Text, TextInput, TouchableOpacity, FlatList, Alert, StyleSheet } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; export default function App() { const [note, setNote] = useState(''); const [notes, setNotes] = useState([]); useEffect(() => { loadNotes(); }, []); useEffect(() => { saveNotes(); }, [notes]); const loadNotes = async () => { try { const data = await AsyncStorage.getItem('notes'); if (data) setNotes(JSON.parse(data)); } catch (err) { console.error(err); } }; const saveNotes = async () => { try { await AsyncStorage.setItem('notes', JSON.stringify(notes)); } catch (err) { console.error(err); } }; const addNote = () => { if (note.trim()) { setNotes([{ id: Date.now().toString(), text: note, date: new Date().toLocaleDateString('id-ID') }, ...notes]); setNote(''); } }; const deleteNote = (id) => { Alert.alert('Hapus', 'Yakin hapus catatan ini?', [ { text: 'Batal' }, { text: 'Hapus', style: 'destructive', onPress: () => setNotes(notes.filter(n => n.id !== id)) }, ]); }; return ( <View style={styles.container}> <Text style={styles.title}>Catatan Saya</Text> <View style={styles.inputRow}> <TextInput style={styles.input} placeholder="Tulis catatan..." value={note} onChangeText={setNote} /> <TouchableOpacity style={styles.addBtn} onPress={addNote}> <Text style={styles.addBtnText}>+</Text> </TouchableOpacity> </View> <FlatList data={notes} keyExtractor={item => item.id} renderItem={({ item }) => ( <TouchableOpacity style={styles.noteCard} onLongPress={() => deleteNote(item.id)}> <Text style={{ fontSize: 15 }}>{item.text}</Text> <Text style={{ fontSize: 11, color: '#aaa', marginTop: 4 }}> {item.date} </Text> </TouchableOpacity> )} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 16, paddingTop: 50, backgroundColor: '#fff8e1' }, title: { fontSize: 28, fontWeight: 'bold', marginBottom: 16 }, inputRow: { flexDirection: 'row', marginBottom: 16 }, input: { flex: 1, borderWidth: 1, borderColor: '#ddd', borderRadius: 10, padding: 12, backgroundColor: '#fff' }, addBtn: { width: 48, height: 48, backgroundColor: '#ff9800', borderRadius: 10, justifyContent: 'center', alignItems: 'center', marginLeft: 8 }, addBtnText: { color: '#fff', fontSize: 24 }, noteCard: { backgroundColor: '#fff', padding: 16, borderRadius: 10, marginBottom: 8, borderLeftWidth: 4, borderLeftColor: '#ff9800' }, });

D. Latihan Mandiri

  1. Buat aplikasi Notes dengan fitur tambah, baca, dan hapus
  2. Data harus tetap ada setelah app di-close dan dibuka ulang
  3. Tambahkan fitur search/filter catatan
  4. Screenshot dan kumpulkan source code