codebydante commited on
Commit
cd37a19
·
1 Parent(s): 3f6c1d4

Fix subscribeToItems to query without index requirement and unblock UI on error

Browse files
Files changed (1) hide show
  1. services/firebase.ts +14 -6
services/firebase.ts CHANGED
@@ -43,9 +43,9 @@ const cleanData = (data: any) => {
43
  };
44
 
45
  export const subscribeToItems = (callback: (items: DataItem[]) => void) => {
46
- const q = query(collection(db, COLLECTION_NAME), orderBy('createdAt', 'desc'));
47
 
48
- return onSnapshot(q, (snapshot) => {
49
  const items = snapshot.docs.map(doc => {
50
  const data = doc.data();
51
 
@@ -54,22 +54,30 @@ export const subscribeToItems = (callback: (items: DataItem[]) => void) => {
54
  if (blocks && Array.isArray(blocks)) {
55
  blocks = blocks.map((block: any) => ({
56
  ...block,
57
- type: block.type || 'text' // Default to 'text' if type is missing
58
  }));
59
  }
60
 
 
 
 
61
  return {
62
  id: doc.id,
63
  ...data,
64
  blocks,
65
- // Convert Firestore Timestamp to number (milliseconds) if necessary
66
- createdAt: data.createdAt?.toMillis ? data.createdAt.toMillis() : Date.now(),
67
- updatedAt: data.updatedAt?.toMillis ? data.updatedAt.toMillis() : (data.createdAt?.toMillis ? data.createdAt.toMillis() : Date.now()),
68
  } as DataItem;
69
  });
 
 
 
 
70
  callback(items);
71
  }, (error) => {
72
  console.error("Error reading from Firestore:", error);
 
 
73
  });
74
  };
75
 
 
43
  };
44
 
45
  export const subscribeToItems = (callback: (items: DataItem[]) => void) => {
46
+ const colRef = collection(db, COLLECTION_NAME);
47
 
48
+ return onSnapshot(colRef, (snapshot) => {
49
  const items = snapshot.docs.map(doc => {
50
  const data = doc.data();
51
 
 
54
  if (blocks && Array.isArray(blocks)) {
55
  blocks = blocks.map((block: any) => ({
56
  ...block,
57
+ type: block.type || 'text'
58
  }));
59
  }
60
 
61
+ const createdTime = data.createdAt?.toMillis ? data.createdAt.toMillis() : (typeof data.createdAt === 'number' ? data.createdAt : Date.now());
62
+ const updatedTime = data.updatedAt?.toMillis ? data.updatedAt.toMillis() : (typeof data.updatedAt === 'number' ? data.updatedAt : createdTime);
63
+
64
  return {
65
  id: doc.id,
66
  ...data,
67
  blocks,
68
+ createdAt: createdTime,
69
+ updatedAt: updatedTime,
 
70
  } as DataItem;
71
  });
72
+
73
+ // Sort descending by createdAt in JS safely
74
+ items.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
75
+
76
  callback(items);
77
  }, (error) => {
78
  console.error("Error reading from Firestore:", error);
79
+ // Return empty array on error so UI unblocks instead of staying black
80
+ callback([]);
81
  });
82
  };
83