Moved the useUser hook
This commit is contained in:
@@ -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";
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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("@");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user