Practice and reinforce the concepts from Lesson 6
Take a working todo app that loses data on restart and add persistence so todos survive app restarts.
import React, { useState } from 'react';
import { View, Text, TextInput, Button, FlatList, TouchableOpacity } from 'react-native';
const TodoApp = () => {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React Native', completed: false },
{ id: 2, text: 'Build an app', completed: false }
]);
const [newTodo, setNewTodo] = useState('');
const addTodo = () => {
if (newTodo.trim()) {
const newId = Math.max(...todos.map(t => t.id), 0) + 1;
setTodos([...todos, { id: newId, text: newTodo, completed: false }]);
setNewTodo('');
}
};
const toggleTodo = (id) => {
setTodos(todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
));
};
return (
<View style={{padding: 20}}>
<Text style={{fontSize: 24, marginBottom: 20}}>My Todos</Text>
<TextInput
value={newTodo}
onChangeText={setNewTodo}
placeholder="Add new todo..."
style={{borderWidth: 1, padding: 10, marginBottom: 10}}
/>
<Button title="Add Todo" onPress={addTodo} />
<FlatList
data={todos}
keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => (
<TouchableOpacity onPress={() => toggleTodo(item.id)}>
<Text style={{
fontSize: 18,
padding: 10,
textDecorationLine: item.completed ? 'line-through' : 'none'
}}>
{item.completed ? '✓ ' : '○ '}{item.text}
</Text>
</TouchableOpacity>
)}
/>
</View>
);
};
export default TodoApp;
@react-native-async-storage/async-storage
// Add this to load data when app starts
useEffect(() => {
loadTodos();
}, []);
const loadTodos = async () => {
try {
const savedTodos = await AsyncStorage.getItem('todos');
if (savedTodos) {
setTodos(JSON.parse(savedTodos));
}
} catch (error) {
console.log('Error loading todos:', error);
}
};
// Call this whenever todos change
const saveTodos = async (todosToSave) => {
try {
await AsyncStorage.setItem('todos', JSON.stringify(todosToSave));
} catch (error) {
console.log('Error saving todos:', error);
}
};
Your enhanced app should:
Add a "Clear All Completed" button that removes finished todos and updates storage.
Complete this activity and submit your work through the Activity Submission Form