import React, { useEffect, useState } from 'react';
import { View, Text, Button, FlatList, TextInput, Alert } from 'react-native';
import Realm from 'realm';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
const TodoSchema = {
name: 'Todo',
properties: {
_id: 'string',
text: 'string',
done: { type: 'bool', default: false }
},
primaryKey: '_id',
};
export default function RealmTodoList() {
const [realm, setRealm] = useState(null);
const [todos, setTodos] = useState([]);
const [newTodoText, setNewTodoText] = useState('');
useEffect(() => {
Realm.open({ schema: [TodoSchema] }).then(r => {
setRealm(r);
const allTodos = r.objects('Todo');
setTodos([...allTodos]);
allTodos.addListener(() => {
setTodos([...allTodos]);
});
});
return () => {
if (realm !== null && !realm.isClosed) {
realm.close();
}
};
}, []);
const addTodo = () => {
if (newTodoText.trim() === '') {
Alert.alert('Please enter a todo text');
return;
}
realm.write(() => {
realm.create('Todo', {
_id: uuidv4(),
text: newTodoText.trim(),
done: false
});
});
setNewTodoText('');
};
return (
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ fontSize: 24, marginBottom: 10 }}>Simple Realm Todo List</Text>
<TextInput
placeholder="Enter new todo"
value={newTodoText}
onChangeText={setNewTodoText}
style={{ borderWidth: 1, borderColor: '#ccc', padding: 8, marginBottom: 10 }}
accessibilityLabel="New todo input"
/>
<Button title="+ Add Todo" onPress={addTodo} accessibilityLabel="Add todo button" />
<FlatList
data={todos}
keyExtractor={item => item._id}
renderItem={({ item }) => <Text>- [ ] {item.text}</Text>}
style={{ marginTop: 20 }}
accessibilityLabel="Todo list"
/>
</View>
);
}
This solution uses Realm to store todo items locally on the device. We define a TodoSchema with an _id as primary key, a text string, and a done boolean.
Inside useEffect, we open Realm and load all todos into state. We also add a listener on the Realm collection to update the UI automatically when data changes.
The addTodo function writes a new todo with a unique ID generated by uuidv4(). After adding, it clears the input.
The UI shows a text input, an add button, and a list of todos. Accessibility labels are added for better screen reader support.