Moved the useUser hook

This commit is contained in:
Matt Aitken
2022-12-08 11:09:12 +00:00
parent 292c16d16f
commit 5c53c8c904
3 changed files with 25 additions and 25 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
import { DocumentTextIcon } from "@heroicons/react/24/solid";
import { Link } from "@remix-run/react";
import { useOptionalUser } from "~/utils";
import { useOptionalUser } from "~/hooks/useUser";
import { Logo } from "./Logo";
import { UserProfileMenu } from "./UserProfileMenu";
+24
View File
@@ -0,0 +1,24 @@
import type { User } from "~/models/user.server";
import { useMatchesData } from "~/utils";
function isUser(user: any): user is User {
return user && typeof user === "object" && typeof user.email === "string";
}
export function useOptionalUser(): User | undefined {
const data = useMatchesData("root");
if (!data || !isUser(data.user)) {
return undefined;
}
return data.user;
}
export function useUser(): User {
const maybeUser = useOptionalUser();
if (!maybeUser) {
throw new Error(
"No user found in root loader, but user is required by useUser. If user is optional, try useOptionalUser instead."
);
}
return maybeUser;
}
-24
View File
@@ -1,8 +1,6 @@
import { useMatches } from "@remix-run/react";
import { useMemo } from "react";
import type { User } from "~/models/user.server";
const DEFAULT_REDIRECT = "/";
/**
@@ -44,28 +42,6 @@ export function useMatchesData(
return route?.data;
}
function isUser(user: any): user is User {
return user && typeof user === "object" && typeof user.email === "string";
}
export function useOptionalUser(): User | undefined {
const data = useMatchesData("root");
if (!data || !isUser(data.user)) {
return undefined;
}
return data.user;
}
export function useUser(): User {
const maybeUser = useOptionalUser();
if (!maybeUser) {
throw new Error(
"No user found in root loader, but user is required by useUser. If user is optional, try useOptionalUser instead."
);
}
return maybeUser;
}
export function validateEmail(email: unknown): email is string {
return typeof email === "string" && email.length > 3 && email.includes("@");
}