Skip to content

Commit c84d962

Browse files
committed
refactor(examples): update collection query to invalidate queries
1 parent cade209 commit c84d962

File tree

4 files changed

+41
-11
lines changed

4 files changed

+41
-11
lines changed

examples/react/kitchen-sink/src/components/CollectionQueryExample.tsx

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { useMutation, useQueryClient } from "@tanstack/react-query";
12
import {
23
useAddDocumentMutation,
34
useCollectionQuery,
@@ -8,6 +9,7 @@ import {
89
doc,
910
getFirestore,
1011
query,
12+
Timestamp,
1113
where,
1214
} from "firebase/firestore";
1315
import { useState } from "react";
@@ -17,7 +19,7 @@ interface Task {
1719
title: string;
1820
completed: boolean;
1921
priority: "low" | "medium" | "high";
20-
createdAt: Date;
22+
createdAt: Timestamp | Date;
2123
}
2224

2325
export function CollectionQueryExample() {
@@ -26,6 +28,7 @@ export function CollectionQueryExample() {
2628
useState<Task["priority"]>("medium");
2729
const [filterCompleted, setFilterCompleted] = useState<boolean | null>(null);
2830

31+
const queryClient = useQueryClient();
2932
const firestore = getFirestore();
3033
const tasksCollection = collection(firestore, "tasks");
3134

@@ -45,8 +48,13 @@ export function CollectionQueryExample() {
4548
queryKey: ["tasks", filterCompleted],
4649
});
4750

48-
// Add task mutation
49-
const addTaskMutation = useAddDocumentMutation(tasksCollection);
51+
// Add task mutation with query invalidation
52+
const addTaskMutation = useAddDocumentMutation(tasksCollection, {
53+
onSuccess: () => {
54+
// Invalidate all task queries after successful add
55+
queryClient.invalidateQueries({ queryKey: ["tasks"] });
56+
},
57+
});
5058

5159
const handleAddTask = async () => {
5260
if (!newTaskTitle.trim()) return;
@@ -76,10 +84,21 @@ export function CollectionQueryExample() {
7684
console.log(`Would toggle task ${taskId} to ${!currentCompleted}`);
7785
};
7886

87+
// Use a mutation for delete with dynamic document reference TODO: why doesn't the library support dynamic document reference?
88+
const deleteTaskMutation = useMutation({
89+
mutationFn: async (taskId: string) => {
90+
const taskRef = doc(firestore, "tasks", taskId);
91+
await deleteDoc(taskRef);
92+
},
93+
onSuccess: () => {
94+
// Invalidate all task queries after successful delete
95+
queryClient.invalidateQueries({ queryKey: ["tasks"] });
96+
},
97+
});
98+
7999
const handleDeleteTask = async (taskId: string) => {
80-
const taskRef = doc(firestore, "tasks", taskId);
81100
try {
82-
await deleteDoc(taskRef);
101+
await deleteTaskMutation.mutateAsync(taskId);
83102
} catch (error) {
84103
console.error("Failed to delete task:", error);
85104
}
@@ -252,7 +271,12 @@ export function CollectionQueryExample() {
252271
{task.title}
253272
</h4>
254273
<p className="text-sm text-gray-500">
255-
Created: {task.createdAt.toLocaleDateString()}
274+
Created:{" "}
275+
{task.createdAt instanceof Timestamp
276+
? task.createdAt.toDate().toLocaleDateString()
277+
: task.createdAt instanceof Date
278+
? task.createdAt.toLocaleDateString()
279+
: "Unknown date"}
256280
</p>
257281
</div>
258282
<span

examples/react/kitchen-sink/src/components/WithConverterExample.tsx

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const productConverter = {
1919
},
2020
fromFirestore(
2121
snapshot: QueryDocumentSnapshot,
22-
options: SnapshotOptions,
22+
options: SnapshotOptions
2323
): Product {
2424
const data = snapshot.data(options);
2525
return {
@@ -32,10 +32,13 @@ const productConverter = {
3232
export function WithConverterExample() {
3333
const firestore = getFirestore();
3434
const ref = query(
35-
collection(firestore, "products").withConverter(productConverter),
35+
collection(firestore, "products").withConverter(productConverter)
3636
);
3737

38-
const { data, isLoading, isError, error } = useCollectionQuery(ref, {
38+
const { data, isLoading, isError, error } = useCollectionQuery<
39+
Product,
40+
DocumentData
41+
>(ref, {
3942
queryKey: ["products"],
4043
});
4144

examples/react/kitchen-sink/src/firebase.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { connectFirestoreEmulator, getFirestore } from "firebase/firestore";
44

55
if (getApps().length === 0) {
66
initializeApp({
7-
projectId: "example",
7+
projectId: "test-project",
88
apiKey: "demo-api-key", // Required for Firebase to initialize
99
});
1010

examples/react/kitchen-sink/tsconfig.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
"strict": true,
1919
"noUnusedLocals": true,
2020
"noUnusedParameters": true,
21-
"noFallthroughCasesInSwitch": true
21+
"noFallthroughCasesInSwitch": true,
22+
23+
/* Types */
24+
"types": ["vite/client"]
2225
},
2326
"include": ["src"],
2427
"references": [{ "path": "./tsconfig.node.json" }]

0 commit comments

Comments
 (0)