Allow use of useCurrentUser/useCurrentTeam hooks in unauthenticated components

This commit is contained in:
Tom Moor
2023-10-28 11:31:42 -04:00
parent 56f9755cd9
commit 964d2b6bb3
17 changed files with 109 additions and 71 deletions

View File

@@ -1,8 +1,23 @@
import invariant from "invariant";
import User from "~/models/User";
import useStores from "./useStores";
export default function useCurrentUser() {
/**
* Returns the current user, or undefined if there is no current user and `rejectOnEmpty` is set to
* false.
*
* @param options.rejectOnEmpty - If true, throws an error if there is no current user. Defaults to true.
*/
function useCurrentUser(options: { rejectOnEmpty: false }): User | undefined;
function useCurrentUser(options?: { rejectOnEmpty: true }): User;
function useCurrentUser({
rejectOnEmpty = true,
}: { rejectOnEmpty?: boolean } = {}) {
const { auth } = useStores();
invariant(auth.user, "user required");
return auth.user;
if (rejectOnEmpty) {
invariant(auth.user, "user required");
}
return auth.user || undefined;
}
export default useCurrentUser;