Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react/firestore): add useUpdateDocumentMutation #159

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/react/src/firestore/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { useCollectionQuery } from "./useCollectionQuery";
export { useGetAggregateFromServerQuery } from "./useGetAggregateFromServerQuery";
export { useGetCountFromServerQuery } from "./useGetCountFromServerQuery";
// useNamedQuery
export { useUpdateDocumentMutation } from "./useUpdateDocumentMutation";
201 changes: 201 additions & 0 deletions packages/react/src/firestore/useUpdateDocumentMutation.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
import { renderHook, waitFor, act } from "@testing-library/react";
import {
doc,
type DocumentReference,
getDoc,
setDoc,
} from "firebase/firestore";
import { beforeEach, describe, expect, test } from "vitest";
import { useUpdateDocumentMutation } from "./useUpdateDocumentMutation";

import {
expectFirestoreError,
firestore,
wipeFirestore,
} from "~/testing-utils";
import { queryClient, wrapper } from "../../utils";

describe("useUpdateDocumentMutation", () => {
beforeEach(async () => {
await wipeFirestore();
queryClient.clear();
});

test("successfully updates an existing document", async () => {
const docRef = doc(firestore, "tests", "updateTest");

await setDoc(docRef, { foo: "initial", num: 1, unchanged: "same" });

const updateData = { foo: "updated", num: 2 };

const { result } = renderHook(
() => useUpdateDocumentMutation(docRef, updateData),
{ wrapper }
);

expect(result.current.isPending).toBe(false);

await act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});

const snapshot = await getDoc(docRef);
expect(snapshot.exists()).toBe(true);
expect(snapshot.data()).toEqual({
foo: "updated",
num: 2,
unchanged: "same",
});
});

test("handles nested field updates", async () => {
const docRef = doc(firestore, "tests", "nestedTest");

await setDoc(docRef, {
nested: { field1: "old", field2: "keep" },
top: "unchanged",
});

const updateData = {
"nested.field1": "new",
};

const { result } = renderHook(
() => useUpdateDocumentMutation(docRef, updateData),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});

const snapshot = await getDoc(docRef);
const data = snapshot.data();
expect(data?.nested.field1).toBe("new");
expect(data?.nested.field2).toBe("keep");
expect(data?.top).toBe("unchanged");
});

test("handles type-safe document updates", async () => {
interface TestDoc {
foo: string;
num: number;
optional?: string;
}

const docRef = doc(
firestore,
"tests",
"typedDoc"
) as DocumentReference<TestDoc>;

await setDoc(docRef, { foo: "initial", num: 1 });

const updateData = { num: 42 };

const { result } = renderHook(
() => useUpdateDocumentMutation(docRef, updateData),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});

const snapshot = await getDoc(docRef);
const data = snapshot.data();
expect(data?.foo).toBe("initial"); // unchanged
expect(data?.num).toBe(42); // updated
});

test("fails when updating non-existent document", async () => {
const nonExistentDocRef = doc(firestore, "tests", "doesNotExist");
const updateData = { foo: "bar" };

const { result } = renderHook(
() => useUpdateDocumentMutation(nonExistentDocRef, updateData),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isError).toBe(true);
});

expectFirestoreError(result.current.error, "not-found");
});

test("handles errors when updating restricted collection", async () => {
const restrictedDocRef = doc(firestore, "restrictedCollection", "someDoc");
const updateData = { foo: "bar" };

const { result } = renderHook(
() => useUpdateDocumentMutation(restrictedDocRef, updateData),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isError).toBe(true);
});

expectFirestoreError(result.current.error, "permission-denied");
});

test("calls onSuccess callback after update", async () => {
const docRef = doc(firestore, "tests", "callbackTest");
await setDoc(docRef, { foo: "initial" });

let callbackCalled = false;
const updateData = { foo: "updated" };

const { result } = renderHook(
() =>
useUpdateDocumentMutation(docRef, updateData, {
onSuccess: () => {
callbackCalled = true;
},
}),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});

expect(callbackCalled).toBe(true);
const snapshot = await getDoc(docRef);
expect(snapshot.data()?.foo).toBe("updated");
});

test("handles empty update object", async () => {
const docRef = doc(firestore, "tests", "emptyUpdateTest");
await setDoc(docRef, { foo: "initial" });

const emptyUpdate = {};

const { result } = renderHook(
() => useUpdateDocumentMutation(docRef, emptyUpdate),
{ wrapper }
);

await act(() => result.current.mutate());

await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});

const snapshot = await getDoc(docRef);
expect(snapshot.data()).toEqual({ foo: "initial" });
});
});
27 changes: 27 additions & 0 deletions packages/react/src/firestore/useUpdateDocumentMutation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useMutation, type UseMutationOptions } from "@tanstack/react-query";
import {
type DocumentReference,
type FirestoreError,
type DocumentData,
updateDoc,
type UpdateData,
} from "firebase/firestore";

type FirestoreUseMutationOptions<TData = unknown, TError = Error> = Omit<
UseMutationOptions<TData, TError, void>,
"mutationFn"
>;

export function useUpdateDocumentMutation<
AppModelType extends DocumentData = DocumentData,
DbModelType extends DocumentData = DocumentData
>(
documentRef: DocumentReference<AppModelType, DbModelType>,
data: UpdateData<DbModelType>,
options?: FirestoreUseMutationOptions<void, FirestoreError>
) {
return useMutation<void, FirestoreError>({
...options,
mutationFn: () => updateDoc(documentRef, data),
});
}