Skip to main content

Overview

The useRecords hook provides a complete interface for managing records in the application. It handles loading, creating, updating, and deleting records, with automatic data refreshing after mutations.

Signature

function useRecords(): {
  records: Record[];
  load: () => Promise<void>;
  create: (title: string, type: string) => Promise<void>;
  update: (record: Record) => Promise<void>;
  remove: (id: string) => Promise<void>;
  existsByTitle: (title: string) => Promise<boolean>;
}

Return Values

records
Record[]
required
Array of all records. The Record type includes:
  • id: string - Unique identifier
  • title: string - Record title
  • subtitle?: string - Optional subtitle
  • metadata?: string - Optional metadata
  • type: string - Record type
  • userId?: string - Optional user ID
  • createdAt: string - Creation timestamp
  • updatedAt: string - Last update timestamp
  • isDeleted: boolean - Soft delete flag
load
() => Promise<void>
required
Asynchronously loads all records from the service and updates the state. Called automatically on mount.
create
(title: string, type: string) => Promise<void>
required
Creates a new record with the specified title and type. Automatically reloads records after creation.Throws an error if creation fails.
update
(record: Record) => Promise<void>
required
Updates an existing record. Accepts a complete Record object with modified fields. Automatically reloads records after update.Throws an error if update fails.
remove
(id: string) => Promise<void>
required
Deletes a record by ID. Automatically reloads records after deletion.Throws an error if deletion fails.
existsByTitle
(title: string) => Promise<boolean>
required
Checks if a record with the given title already exists. Useful for validation before creating new records.Returns true if a record exists, false otherwise.

Usage Example

import { useRecords } from '@/src/presentation/hooks/useRecords';
import { useState } from 'react';
import { Button, TextInput, FlatList, View } from 'react-native';

export default function RecordsScreen() {
  const { records, create, remove, update, existsByTitle } = useRecords();
  const [title, setTitle] = useState('');
  const [type, setType] = useState('');

  const handleSubmit = async () => {
    // Check if record already exists
    const exists = await existsByTitle(title.trim());
    if (exists) {
      alert('Record already exists');
      return;
    }

    try {
      await create(title.trim(), type.trim());
      setTitle('');
      setType('');
    } catch (error) {
      console.error('Failed to create record:', error);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await remove(id);
    } catch (error) {
      console.error('Failed to delete record:', error);
    }
  };

  const handleUpdate = async (record: Record) => {
    try {
      await update({
        ...record,
        title: 'Updated Title'
      });
    } catch (error) {
      console.error('Failed to update record:', error);
    }
  };

  return (
    <View>
      <TextInput
        placeholder="Title"
        value={title}
        onChangeText={setTitle}
      />
      <TextInput
        placeholder="Type"
        value={type}
        onChangeText={setType}
      />
      <Button title="Create" onPress={handleSubmit} />

      <FlatList
        data={records}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View>
            <Text>{item.title}</Text>
            <Button title="Delete" onPress={() => handleDelete(item.id)} />
          </View>
        )}
      />
    </View>
  );
}

Implementation Details

  • Records are loaded automatically when the component mounts
  • All mutation operations (create, update, remove) automatically reload the records list
  • The hook uses RecordService internally for data operations
  • Errors are caught and re-thrown with formatted messages using getErrorMessage

Source

Defined in src/presentation/hooks/useRecords.ts:6

Build docs developers (and LLMs) love