Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

index.tsx

102 lines2.5 KB

1import React, { useEffect, useState } from 'react'
2import { ActivityIndicator, StyleSheet, Text, View } from 'react-native'
3import { SafeAreaView } from 'react-native-safe-area-context'
4import { TodoList } from '../src/components/TodoList'
5import { createTodos } from '../src/db/todos'
6import type { TodosHandle } from '../src/db/todos'
7​
8export default function HomeScreen() {
9 const [handle, setHandle] = useState<TodosHandle | null>(null)
10 const [error, setError] = useState<string | null>(null)
11​
12 useEffect(() => {
13 let disposed = false
14 let currentHandle: TodosHandle | null = null
15​
16 try {
17 const h = createTodos()
18 if (disposed as boolean) {
19 h.close()
20 return
21 }
22 currentHandle = h
23 setHandle(h)
24 } catch (err) {
25 if (!(disposed as boolean)) {
26 console.error(`Failed to initialize:`, err)
27 setError(err instanceof Error ? err.message : `Failed to initialize`)
28 }
29 }
30​
31 return () => {
32 disposed = true
33 currentHandle?.close()
34 }
35 }, [])
36​
37 if (error) {
38 return (
39 <SafeAreaView style={{ flex: 1 }} edges={[`bottom`]}>
40 <View style={styles.errorContainer}>
41 <Text style={styles.errorTitle}>Initialization Error</Text>
42 <View style={styles.errorBox}>
43 <Text style={styles.errorText}>{error}</Text>
44 </View>
45 </View>
46 </SafeAreaView>
47 )
48 }
49​
50 if (!handle) {
51 return (
52 <SafeAreaView style={{ flex: 1 }} edges={[`bottom`]}>
53 <View style={styles.loadingContainer}>
54 <ActivityIndicator size="large" color="#3b82f6" />
55 <Text style={styles.loadingText}>Initializing...</Text>
56 </View>
57 </SafeAreaView>
58 )
59 }
60​
61 return (
62 <SafeAreaView style={{ flex: 1 }} edges={[`bottom`]}>
63 <TodoList collection={handle.collection} executor={handle.executor} />
64 </SafeAreaView>
65 )
67​
68const styles = StyleSheet.create({
69 errorContainer: {
70 flex: 1,
71 padding: 16,
72 backgroundColor: `#f5f5f5`,
73 },
74 errorTitle: {
75 fontSize: 24,
76 fontWeight: `bold`,
77 color: `#111`,
78 marginBottom: 16,
79 },
80 errorBox: {
81 backgroundColor: `#fee2e2`,
82 borderWidth: 1,
83 borderColor: `#fca5a5`,
84 borderRadius: 8,
85 padding: 12,
86 },
87 errorText: {
88 color: `#dc2626`,
89 fontSize: 14,
90 },
91 loadingContainer: {
92 flex: 1,
93 justifyContent: `center`,
94 alignItems: `center`,
95 gap: 12,
96 backgroundColor: `#f5f5f5`,
97 },
98 loadingText: {
99 color: `#666`,
100 fontSize: 14,
101 },
102})