Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Get personal collection hook (#66701)

Ryan Laurieb8113ad52607
diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts
index 75e1c27cc1f..a69971d6f0f 100644
--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts
+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts
@@ -8,7 +8,7 @@ import {
useListDatabasesQuery,
} from "metabase/api";
import { isRootCollection } from "metabase/collections/utils";
-import { useSetting } from "metabase/common/hooks";
+import { useGetPersonalCollection, useSetting } from "metabase/common/hooks";
import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";
import { useSelector } from "metabase/lib/redux";
import { PLUGIN_DATA_STUDIO, PLUGIN_TENANTS } from "metabase/plugins";
@@ -52,20 +52,16 @@ const getTenantSpecificCollectionsRoot = (): CollectionPickerItem | null => {
export const useRootCollectionPickerItems = (
options: CollectionItemListProps["options"],
) => {
- const currentUser = useSelector(getUser);
const isAdmin = useSelector(getUserIsAdmin);
const { data: databaseData, isLoading: isLoadingDatabases } =
useListDatabasesQuery(undefined, { skip: !options.showDatabases });
const databases = databaseData?.data ?? [];
const tenantsEnabled = useSetting("use-tenants");
+ const currentUser = useSelector(getUser);
- const { data: personalCollection, isLoading: isLoadingPersonalCollecton } =
- useGetCollectionQuery(
- currentUser?.personal_collection_id
- ? { id: currentUser.personal_collection_id }
- : skipToken,
- );
+ const { data: personalCollection, isLoading: isLoadingPersonalCollection } =
+ useGetPersonalCollection();
const { data: libraryCollection } =
PLUGIN_DATA_STUDIO.useGetLibraryCollection({
@@ -76,9 +72,9 @@ export const useRootCollectionPickerItems = (
data: personalCollectionItems,
isLoading: isLoadingPersonalCollectionItems,
} = useListCollectionItemsQuery(
- currentUser?.personal_collection_id
+ personalCollection
? {
- id: currentUser?.personal_collection_id,
+ id: personalCollection.id,
models: ["collection", "dashboard"],
limit: 0, // we only want total number of items
}
@@ -88,7 +84,7 @@ export const useRootCollectionPickerItems = (
const {
data: rootCollection,
- isLoading: isLoadingRootCollecton,
+ isLoading: isLoadingRootCollection,
error: rootCollectionError,
} = useGetCollectionQuery({ id: "root" });
@@ -231,7 +227,6 @@ export const useRootCollectionPickerItems = (
return collectionItems;
}, [
- currentUser,
personalCollection,
rootCollection,
isAdmin,
@@ -241,12 +236,13 @@ export const useRootCollectionPickerItems = (
totalPersonalCollectionItems,
libraryCollection,
tenantsEnabled,
+ currentUser,
]);
const isLoading =
isLoadingDatabases ||
- isLoadingRootCollecton ||
- isLoadingPersonalCollecton ||
+ isLoadingRootCollection ||
+ isLoadingPersonalCollection ||
isLoadingPersonalCollectionItems;
return { items, isLoading };
diff --git a/frontend/src/metabase/common/hooks/index.ts b/frontend/src/metabase/common/hooks/index.ts
index d936df0c837..5b7cfbd53de 100644
--- a/frontend/src/metabase/common/hooks/index.ts
+++ b/frontend/src/metabase/common/hooks/index.ts
@@ -1,6 +1,7 @@
export * from "./entity-framework";
export * from "./use-confirmation";
export * from "./use-docs-url";
+export * from "./use-get-personal-collection";
export * from "./use-has-token-feature";
export * from "./use-locale";
export * from "./use-notification-channels";
diff --git a/frontend/src/metabase/common/hooks/use-get-personal-collection/index.ts b/frontend/src/metabase/common/hooks/use-get-personal-collection/index.ts
new file mode 100644
index 00000000000..53bc186ebef
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-get-personal-collection/index.ts
@@ -0,0 +1 @@
+export * from "./use-get-personal-collection";
diff --git a/frontend/src/metabase/common/hooks/use-get-personal-collection/use-get-personal-collection.ts b/frontend/src/metabase/common/hooks/use-get-personal-collection/use-get-personal-collection.ts
new file mode 100644
index 00000000000..1846ccf1313
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-get-personal-collection/use-get-personal-collection.ts
@@ -0,0 +1,20 @@
+import { skipToken, useGetCollectionQuery } from "metabase/api";
+import { useSelector } from "metabase/lib/redux";
+import { getUserPersonalCollectionId } from "metabase/selectors/user";
+
+/**
+ * Hook that fetches the personal collection for the currently logged-in user.
+ * Returns the RTK Query result with the collection data, loading state, and any errors.
+ */
+export const useGetPersonalCollection = () => {
+ const personalCollectionId = useSelector(getUserPersonalCollectionId);
+ const response = useGetCollectionQuery(
+ personalCollectionId
+ ? {
+ id: personalCollectionId,
+ }
+ : skipToken,
+ );
+
+ return response;
+};
diff --git a/frontend/src/metabase/common/hooks/use-get-personal-collection/use-get-personal-collection.unit.spec.tsx b/frontend/src/metabase/common/hooks/use-get-personal-collection/use-get-personal-collection.unit.spec.tsx
new file mode 100644
index 00000000000..4c1706f49be
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-get-personal-collection/use-get-personal-collection.unit.spec.tsx
@@ -0,0 +1,104 @@
+import {
+ findRequests,
+ setupCollectionByIdEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import type { CollectionId } from "metabase-types/api";
+import { createMockCollection, createMockUser } from "metabase-types/api/mocks";
+import { createMockState } from "metabase-types/store/mocks";
+
+import { useGetPersonalCollection } from "./use-get-personal-collection";
+
+const PERSONAL_COLLECTION_ID = 123;
+
+const PERSONAL_COLLECTION = createMockCollection({
+ id: PERSONAL_COLLECTION_ID,
+ name: "Jack's Personal Collection",
+ is_personal: true,
+ personal_owner_id: 1,
+});
+
+const TestComponent = () => {
+ const { data, isLoading, error } = useGetPersonalCollection();
+ if (isLoading) {
+ return <div>Loading</div>;
+ }
+
+ if (error) {
+ return <div>{JSON.stringify(error)}</div>;
+ }
+
+ if (!data) {
+ return <div>No Personal Collection</div>;
+ }
+
+ return <div>{JSON.stringify(data)}</div>;
+};
+
+interface SetupOpts {
+ personalCollectionId?: CollectionId;
+ error?: string;
+}
+
+const setup = ({ personalCollectionId, error }: SetupOpts = {}) => {
+ const user = createMockUser({
+ id: 1,
+ first_name: "John",
+ personal_collection_id: personalCollectionId,
+ });
+
+ if (personalCollectionId && !error) {
+ setupCollectionByIdEndpoint({ collections: [PERSONAL_COLLECTION] });
+ } else if (error) {
+ setupCollectionByIdEndpoint({ collections: [], error });
+ }
+
+ const state = createMockState({
+ currentUser: user,
+ });
+
+ renderWithProviders(<TestComponent />, {
+ storeInitialState: state,
+ });
+};
+
+describe("useGetPersonalCollection", () => {
+ it("should be initially loading when user has a personal collection ID", () => {
+ setup({ personalCollectionId: PERSONAL_COLLECTION_ID });
+ expect(screen.getByText("Loading")).toBeInTheDocument();
+ });
+
+ it("should fetch and display the personal collection", async () => {
+ setup({ personalCollectionId: PERSONAL_COLLECTION_ID });
+
+ expect(
+ await screen.findByText(JSON.stringify(PERSONAL_COLLECTION)),
+ ).toBeInTheDocument();
+
+ const requests = await findRequests("GET");
+ expect(requests).toHaveLength(1);
+ expect(requests[0].url).toContain(
+ `/api/collection/${PERSONAL_COLLECTION_ID}`,
+ );
+ });
+
+ it("should handle errors when fetching the collection", async () => {
+ const ERROR = "Failed to load collection";
+ setup({ personalCollectionId: PERSONAL_COLLECTION_ID, error: ERROR });
+
+ expect(await screen.findByText(new RegExp(ERROR))).toBeInTheDocument();
+ const requests = await findRequests("GET");
+ expect(requests).toHaveLength(1);
+ });
+
+ it("should not fetch when user has no personal collection ID", async () => {
+ setup({ personalCollectionId: undefined });
+
+ expect(
+ await screen.findByText("No Personal Collection"),
+ ).toBeInTheDocument();
+
+ const requests = await findRequests("GET");
+ expect(requests).toHaveLength(0);
+ });
+});