Skip to main content

Lesson 8 of 9

Mini Project: Todo App with Zustand + AsyncStorage

Build a production-grade Todo app: Zustand store with typed actions and persist middleware, AsyncStorage-backed persistence, filter views, animated completion, and accessible controls.

50 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Todo Store + Screen

Todo Store + Screen
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { View, Text, TextInput, Pressable, FlatList, StyleSheet } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useState, useCallback } from 'react';

// ---- Types ----
type Filter = 'all' | 'active' | 'done';
interface Todo { id: string; text: string; done: boolean; createdAt: number; }

// ---- Store ----
interface TodoStore {
  todos: Todo[];
  filter: Filter;
  addTodo: (text: string) => void;
  toggleTodo: (id: string) => void;
  deleteTodo: (id: string) => void;
  clearCompleted: () => void;
  setFilter: (f: Filter) => void;
}

const useTodoStore = create<TodoStore>()(
  persist(
    (set, get) => ({
      todos: [],
      filter: 'all',

      addTodo: (text) => set(s => ({
        todos: [...s.todos, { id: Date.now().toString(), text: text.trim(), done: false, createdAt: Date.now() }],
      })),

      toggleTodo: (id) => set(s => ({
        todos: s.todos.map(t => t.id === id ? { ...t, done: !t.done } : t),
      })),

      deleteTodo: (id) => set(s => ({ todos: s.todos.filter(t => t.id !== id) })),

      clearCompleted: () => set(s => ({ todos: s.todos.filter(t => !t.done) })),

      setFilter: (filter) => set({ filter }),
    }),
    {
      name: 'todos',
      storage: createJSONStorage(() => AsyncStorage),
      partialize: (s) => ({ todos: s.todos, filter: s.filter }),
    }
  )
);

// ---- Todo Item ----
const TodoItem = React.memo(({ todo, onToggle, onDelete }: { todo: Todo; onToggle: (id: string) => void; onDelete: (id: string) => void }) => (
  <View style={s.item}>
    <Pressable
      onPress={() => onToggle(todo.id)}
      style={[s.checkbox, todo.done && s.checkboxDone]}
      accessibilityRole="checkbox"
      accessibilityLabel={todo.text}
      accessibilityState={{ checked: todo.done }}
    >
      {todo.done && <Text style={s.checkmark}>โœ“</Text>}
    </Pressable>
    <Text style={[s.itemText, todo.done && s.itemTextDone]} numberOfLines={2}>{todo.text}</Text>
    <Pressable onPress={() => onDelete(todo.id)} style={s.deleteBtn} accessibilityLabel={`Delete ${todo.text}`}>
      <Text style={s.deleteText}>โœ•</Text>
    </Pressable>
  </View>
));

// ---- Main Screen ----
export default function TodoScreen() {
  const [inputText, setInputText] = useState('');
  const todos = useTodoStore(s => s.todos);
  const filter = useTodoStore(s => s.filter);
  const { addTodo, toggleTodo, deleteTodo, clearCompleted, setFilter } = useTodoStore();

  const filteredTodos = useMemo(() => {
    if (filter === 'active') return todos.filter(t => !t.done);
    if (filter === 'done') return todos.filter(t => t.done);
    return todos;
  }, [todos, filter]);

  const keyExtractor = useCallback((t: Todo) => t.id, []);
  const renderItem = useCallback(({ item }: { item: Todo }) => (
    <TodoItem todo={item} onToggle={toggleTodo} onDelete={deleteTodo} />
  ), [toggleTodo, deleteTodo]);

  function handleAdd() {
    if (!inputText.trim()) return;
    addTodo(inputText);
    setInputText('');
  }

  const remaining = todos.filter(t => !t.done).length;
  const completedCount = todos.length - remaining;

  return (
    <SafeAreaView style={s.screen}>
      {/* Header */}
      <View style={s.header}>
        <Text style={s.title}>My Todos</Text>
        <Text style={s.subtitle}>{remaining} remaining</Text>
      </View>

      {/* Input */}
      <View style={s.inputRow}>
        <TextInput
          value={inputText}
          onChangeText={setInputText}
          onSubmitEditing={handleAdd}
          placeholder="Add a todo..."
          placeholderTextColor="#475569"
          returnKeyType="done"
          style={s.input}
          accessibilityLabel="New todo input"
        />
        <Pressable onPress={handleAdd} style={s.addBtn} accessibilityRole="button" accessibilityLabel="Add todo">
          <Text style={s.addBtnText}>+</Text>
        </Pressable>
      </View>

      {/* Filter tabs */}
      <View style={s.filterRow}>
        {(['all', 'active', 'done'] as Filter[]).map(f => (
          <Pressable key={f} onPress={() => setFilter(f)} style={[s.filterTab, filter === f && s.filterTabActive]}>
            <Text style={[s.filterText, filter === f && s.filterTextActive]}>{f.charAt(0).toUpperCase() + f.slice(1)}</Text>
          </Pressable>
        ))}
      </View>

      {/* List */}
      <FlatList
        data={filteredTodos}
        keyExtractor={keyExtractor}
        renderItem={renderItem}
        contentContainerStyle={{ padding: 16, gap: 8, paddingBottom: 40 }}
        ListEmptyComponent={<Text style={s.empty}>No {filter === 'all' ? '' : filter} todos</Text>}
      />

      {/* Footer */}
      {completedCount > 0 && (
        <Pressable onPress={clearCompleted} style={s.clearBtn}>
          <Text style={s.clearText}>Clear {completedCount} completed</Text>
        </Pressable>
      )}
    </SafeAreaView>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1, backgroundColor: '#0f172a' },
  header: { padding: 20, paddingBottom: 0 },
  title: { fontSize: 28, fontWeight: '800', color: '#f1f5f9' },
  subtitle: { fontSize: 14, color: '#64748b', marginTop: 2 },
  inputRow: { flexDirection: 'row', gap: 10, padding: 16 },
  input: { flex: 1, backgroundColor: '#1e293b', borderRadius: 10, padding: 14, fontSize: 15, color: '#f1f5f9', borderWidth: 1, borderColor: '#334155' },
  addBtn: { backgroundColor: '#229c6b', width: 48, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
  addBtnText: { color: 'white', fontSize: 24, fontWeight: '700' },
  filterRow: { flexDirection: 'row', marginHorizontal: 16, borderRadius: 10, backgroundColor: '#1e293b', padding: 4, gap: 4 },
  filterTab: { flex: 1, paddingVertical: 8, borderRadius: 8, alignItems: 'center' },
  filterTabActive: { backgroundColor: '#229c6b' },
  filterText: { fontSize: 13, color: '#64748b', fontWeight: '600' },
  filterTextActive: { color: 'white' },
  item: { flexDirection: 'row', alignItems: 'center', gap: 12, backgroundColor: '#1e293b', borderRadius: 10, padding: 14 },
  checkbox: { width: 22, height: 22, borderRadius: 6, borderWidth: 2, borderColor: '#229c6b', alignItems: 'center', justifyContent: 'center' },
  checkboxDone: { backgroundColor: '#229c6b' },
  checkmark: { color: 'white', fontWeight: '800', fontSize: 13 },
  itemText: { flex: 1, fontSize: 15, color: '#f1f5f9' },
  itemTextDone: { textDecorationLine: 'line-through', color: '#475569' },
  deleteBtn: { padding: 4 },
  deleteText: { color: '#ef4444', fontSize: 16, fontWeight: '700' },
  empty: { textAlign: 'center', color: '#475569', marginTop: 60, fontSize: 16 },
  clearBtn: { margin: 16, backgroundColor: '#1e293b', borderRadius: 10, padding: 14, alignItems: 'center' },
  clearText: { color: '#f87171', fontWeight: '700' },
});

Tip

Tip

Practice Mini Project Todo App with Zustand AsyncStorage in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Complete offline-first todo application with optimistic updates and instant persistence

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Todo App with Zustand AsyncStorage from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Todo App with Zustand AsyncStorage is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done