0
0
React Nativemobile~20 mins

Realm database in React Native - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Realm Todo List
A screen that shows a list of todo items stored in Realm database. Users can add new todos and see them saved persistently.
Target UI
-------------------------
| Simple Realm Todo List |
-------------------------
| + Add Todo             |
|-----------------------|
| - [ ] Buy groceries    |
| - [ ] Walk the dog     |
|-----------------------|
Use Realm database to store todo items locally
Display a list of todos from Realm
Add a button to add a new todo with a text input prompt
Save new todos to Realm and update the list immediately
Each todo has a text and a boolean 'done' status (default false)
Starter Code
React Native
import React, { useEffect, useState } from 'react';
import { View, Text, Button, FlatList, TextInput, Alert } from 'react-native';
import Realm from 'realm';

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(() => {
    // TODO: Open Realm and load todos

    return () => {
      // TODO: Close Realm when component unmounts
    };
  }, []);

  const addTodo = () => {
    // TODO: Add new todo to Realm and update list
  };

  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 }}
      />
      <Button title="+ Add Todo" onPress={addTodo} />
      <FlatList
        data={todos}
        keyExtractor={item => item._id}
        renderItem={({ item }) => <Text>- [ ] {item.text}</Text>}
        style={{ marginTop: 20 }}
      />
    </View>
  );
}
Task 1
Task 2
Task 3
Task 4
Solution
React Native
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.

Final Result
Completed Screen
-------------------------
| Simple Realm Todo List |
-------------------------
| [input] Enter new todo |
| + Add Todo             |
|-----------------------|
| - [ ] Buy groceries    |
| - [ ] Walk the dog     |
| - [ ] Call mom         |
|-----------------------|
User types text in input field
User taps '+ Add Todo' button
New todo is saved in Realm and appears immediately in the list below
List updates automatically if todos change in Realm
Stretch Goal
Add the ability to toggle todo 'done' status by tapping on a todo item
💡 Hint
Use Realm write transactions to update the 'done' boolean and update the UI accordingly