> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/marcosfabricio3/simple-manager-mobile/llms.txt
> Use this file to discover all available pages before exploring further.

# Data Flow

> How data moves through Simple Manager Mobile's architecture layers

## Data Flow Overview

Data flows through the application in a unidirectional pattern, ensuring predictable behavior and making the system easier to reason about.

## Flow Diagram

```mermaid theme={null}
sequenceDiagram
    participant UI as UI Component
    participant Hook as Custom Hook
    participant Service as Service Layer
    participant Repo as Repository
    participant DB as SQLite Database
    
    UI->>Hook: User action (e.g., create record)
    Hook->>Service: create(title, type)
    Service->>Service: Generate UUID & timestamps
    Service->>Repo: create(record)
    Repo->>DB: INSERT INTO records
    DB-->>Repo: Success
    Repo-->>Service: Success
    Service-->>Hook: Return created record
    Hook->>Service: list() to refresh
    Service->>Repo: findAll()
    Repo->>DB: SELECT * FROM records
    DB-->>Repo: Result rows
    Repo-->>Service: Record[]
    Service-->>Hook: Record[]
    Hook->>Hook: setState(records)
    Hook-->>UI: Updated records
    UI->>UI: Re-render with new data
```

## Data Flow Patterns

### Create Operation

<Steps>
  <Step title="User Input">
    User fills a form and submits in the UI component
  </Step>

  <Step title="Hook Call">
    UI component calls the `create()` method from `useRecords` hook
  </Step>

  <Step title="Service Processing">
    Service generates UUID, timestamps, and creates Record entity
  </Step>

  <Step title="Repository Persistence">
    Repository executes SQL INSERT statement
  </Step>

  <Step title="Database Storage">
    SQLite stores the record
  </Step>

  <Step title="State Refresh">
    Hook reloads data and updates component state
  </Step>

  <Step title="UI Update">
    Component re-renders with updated data
  </Step>
</Steps>

### Read Operation

<Steps>
  <Step title="Component Mount">
    Component mounts and hook's `useEffect` runs
  </Step>

  <Step title="Load Data">
    Hook calls `load()` which invokes `service.list()`
  </Step>

  <Step title="Repository Query">
    Repository executes `SELECT * FROM records WHERE isDeleted = 0`
  </Step>

  <Step title="Data Mapping">
    Repository maps database rows to Record entities
  </Step>

  <Step title="State Update">
    Hook updates local state with records
  </Step>

  <Step title="Render">
    Component renders the list of records
  </Step>
</Steps>

### Update Operation

<Steps>
  <Step title="Edit Action">
    User modifies a record and saves changes
  </Step>

  <Step title="Hook Update">
    UI calls `update(record)` from hook
  </Step>

  <Step title="Timestamp Update">
    Service updates the `updatedAt` timestamp
  </Step>

  <Step title="Repository Update">
    Repository executes SQL UPDATE statement
  </Step>

  <Step title="Refresh">
    Hook reloads all records to reflect changes
  </Step>

  <Step title="Re-render">
    UI updates with modified data
  </Step>
</Steps>

### Delete Operation (Soft Delete)

<Steps>
  <Step title="Delete Action">
    User confirms deletion
  </Step>

  <Step title="Hook Call">
    UI calls `remove(id)` from hook
  </Step>

  <Step title="Service Delete">
    Service calls repository's `softDelete(id)`
  </Step>

  <Step title="Flag Update">
    Repository sets `isDeleted = 1` via UPDATE query
  </Step>

  <Step title="Refresh">
    Hook reloads records (deleted ones are filtered out)
  </Step>

  <Step title="UI Update">
    Component re-renders without the deleted record
  </Step>
</Steps>

## Complete Example: Creating a Record

Let's trace a complete data flow for creating a new record:

### 1. UI Component (Presentation Layer)

<CodeGroup>
  ```tsx src/presentation/screens/RecordsScreen.tsx theme={null}
  import { useRecords } from '@/src/presentation/hooks/useRecords';

  export function RecordsScreen() {
    const { records, create } = useRecords();
    const [title, setTitle] = useState('');

    const handleCreate = async () => {
      try {
        // Step 1: Call hook's create method
        await create(title, 'client');
        setTitle(''); // Clear input
      } catch (error) {
        alert(error.message);
      }
    };

    return (
      <View>
        <TextInput value={title} onChangeText={setTitle} />
        <Button title="Create" onPress={handleCreate} />
        {records.map(record => <RecordCard key={record.id} record={record} />)}
      </View>
    );
  }
  ```
</CodeGroup>

### 2. Custom Hook (Presentation Layer)

<CodeGroup>
  ```typescript src/presentation/hooks/useRecords.ts theme={null}
  import { RecordService } from '@/src/application/services/RecordService';

  export function useRecords() {
    const service = useMemo(() => new RecordService(), []);
    const [records, setRecords] = useState<Record[]>([]);

    const load = async () => {
      // Step 6: Reload data after creation
      const data = await service.list();
      setRecords(data); // Step 7: Update state
    };

    const create = async (title: string, type: string) => {
      // Step 2: Forward to service
      await service.create(title, type);
      await load(); // Step 5: Refresh after creation
    };

    return { records, create, load };
  }
  ```
</CodeGroup>

### 3. Service (Application Layer)

<CodeGroup>
  ```typescript src/application/services/RecordService.ts theme={null}
  import { RecordRepository } from '@/src/infraestructure/repositories/RecordRepository';
  import * as Crypto from 'expo-crypto';

  export class RecordService {
    private repository = new RecordRepository();

    async create(title: string, type: string) {
      // Step 3: Business logic - generate ID and timestamps
      const now = new Date().toISOString();
      
      const record: Record = {
        id: Crypto.randomUUID(),
        title,
        type,
        createdAt: now,
        updatedAt: now,
        isDeleted: false,
      };

      // Step 4: Delegate to repository
      await this.repository.create(record);
      
      return record;
    }
  }
  ```
</CodeGroup>

### 4. Repository (Infrastructure Layer)

<CodeGroup>
  ```typescript src/infraestructure/repositories/RecordRepository.ts theme={null}
  import { db } from '../database/database';

  export class RecordRepository {
    async create(record: Record) {
      // Step 4a: Execute SQL INSERT
      await db.runAsync(
        `INSERT INTO records (
          id, title, subtitle, metadata, type, userId,
          createdAt, updatedAt, isDeleted
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          record.id,
          record.title,
          record.subtitle ?? null,
          record.metadata ?? null,
          record.type,
          record.userId ?? null,
          record.createdAt,
          record.updatedAt,
          record.isDeleted ? 1 : 0,
        ]
      );
    }
  }
  ```
</CodeGroup>

### 5. Database (Infrastructure Layer)

<CodeGroup>
  ```typescript src/infraestructure/database/database.ts theme={null}
  import * as SQLite from "expo-sqlite";

  // Step 4b: SQLite executes the INSERT
  export const db = SQLite.openDatabaseSync("simple_manager.db");
  ```
</CodeGroup>

## Error Handling Flow

Errors propagate upward through the layers:

```mermaid theme={null}
flowchart BT
    DB[Database Error] -->|Throws| Repo[Repository]
    Repo -->|Re-throws| Service[Service]
    Service -->|Transforms| Hook[Hook]
    Hook -->|Catches| UI[UI Component]
    UI -->|Displays| User[User]
    
    style DB fill:#f44336
    style User fill:#4CAF50
```

<CodeGroup>
  ```typescript Error Flow Example theme={null}
  // 1. Database error occurs
  db.runAsync(...) // Throws: "UNIQUE constraint failed"

  // 2. Repository lets it bubble up
  async create(record: Record) {
    await db.runAsync(...); // Error propagates
  }

  // 3. Service might transform it
  async create(title: string, type: string) {
    try {
      await this.repository.create(record);
    } catch (error) {
      // Could log or transform error here
      throw error;
    }
  }

  // 4. Hook catches and handles
  const create = async (title: string, type: string) => {
    try {
      await service.create(title, type);
      await load();
    } catch (error) {
      throw new Error(getErrorMessage(error));
    }
  };

  // 5. UI displays to user
  const handleCreate = async () => {
    try {
      await create(title, 'client');
    } catch (error) {
      alert(error.message); // User sees friendly message
    }
  };
  ```
</CodeGroup>

## State Management

### Local Component State

* Form inputs
* Loading states
* Modal visibility
* Temporary UI state

### Hook State

* Fetched data (records list)
* Loading indicators
* Error states

### Global State (Zustand)

* User session
* App-wide settings
* Theme preferences

### Database State (Source of Truth)

* Persisted records
* User data
* Application data

<Warning>
  The database is always the **single source of truth**. UI state is ephemeral and rebuilt from database on app restart.
</Warning>

## Data Refresh Strategy

The application uses a simple refresh strategy:

1. After any mutation (create, update, delete)
2. Reload all data from the database
3. Update component state
4. Trigger re-render

<CodeGroup>
  ```typescript Refresh Pattern theme={null}
  const create = async (title: string, type: string) => {
    await service.create(title, type);
    await load(); // Always refresh after mutation
  };

  const update = async (record: Record) => {
    await service.update(record);
    await load(); // Always refresh after mutation
  };

  const remove = async (id: string) => {
    await service.delete(id);
    await load(); // Always refresh after mutation
  };
  ```
</CodeGroup>

<Info>
  This strategy is simple and reliable. For larger datasets, consider implementing optimistic updates or pagination.
</Info>

## Future: API Integration

When migrating to an API backend, the data flow remains similar:

```mermaid theme={null}
sequenceDiagram
    participant UI as UI Component
    participant Hook as Custom Hook
    participant Service as Service Layer
    participant HTTP as HTTP Client
    participant API as Backend API
    participant DB as Database
    
    UI->>Hook: User action
    Hook->>Service: create(data)
    Service->>HTTP: POST /api/records
    HTTP->>API: HTTP Request
    API->>DB: INSERT
    DB-->>API: Success
    API-->>HTTP: JSON Response
    HTTP-->>Service: Record
    Service-->>Hook: Record
    Hook-->>UI: Update state
```

<Tip>
  Only the **Infrastructure Layer** needs to change. Services, hooks, and UI remain unchanged.
</Tip>

## Related Pages

<CardGroup cols={2}>
  <Card title="Clean Architecture" icon="layer-group" href="/architecture/clean-architecture">
    Understand the architectural layers
  </Card>

  <Card title="Folder Structure" icon="folder-tree" href="/architecture/folder-structure">
    See where each piece lives
  </Card>
</CardGroup>
