Skip to content

Commit

Permalink
feat: add storage module
Browse files Browse the repository at this point in the history
  • Loading branch information
andipaetzold committed Oct 14, 2021
1 parent f5395fa commit 32a6d4d
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export * from "./common";
export * from "./firestore";
export * from "./storage";

1 change: 1 addition & 0 deletions src/storage/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useDownloadURL";
16 changes: 16 additions & 0 deletions src/storage/internal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { StorageReference } from "@firebase/storage";
import { useStableValue } from "../util/useStableValue";

/**
* @internal
*/
function isStorageRefEqual(a: StorageReference | undefined, b: StorageReference | undefined): boolean {
return a?.fullPath === b?.fullPath;
}

/**
* @internal
*/
export function useStableStorageRef(query: StorageReference | undefined): StorageReference | undefined {
return useStableValue(query, isStorageRefEqual);
}
44 changes: 44 additions & 0 deletions src/storage/useDownloadURL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { getDownloadURL, StorageError, StorageReference } from "firebase/storage";
import { useEffect, useMemo } from "react";
import { ValueHookResult } from "../common";
import { useIsMounted } from "../util/useIsMounted";
import { useLoadingValue } from "../util/useLoadingValue";
import { useStableStorageRef } from "./internal";

export type UseDownloadURLResult = ValueHookResult<string, StorageError>;

export function useDownloadURL(reference: StorageReference): UseDownloadURLResult {
const isMounted = useIsMounted();
const { value, setValue, loading, setLoading, error, setError } = useLoadingValue<string, StorageError>();

const stableStorageRef = useStableStorageRef(reference ?? undefined);

useEffect(() => {
(async () => {
if (stableStorageRef === undefined) {
setValue();
} else {
setLoading();

try {
const url = await getDownloadURL(stableStorageRef);

if (!isMounted.current) {
return;
}

setValue(url);
} catch (e) {
if (!isMounted.current) {
return;
}

// We assume this is always a StorageError
setError(e as unknown as StorageError);
}
}
})();
}, [stableStorageRef]);

return useMemo(() => [value, loading, error], [value, loading, error]);
}

0 comments on commit 32a6d4d

Please sign in to comment.