infoalloggi-monorepo/apps/infoalloggi/src/lib/userViewContext.tsx

41 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-11-20 16:48:29 +01:00
import { createContext, type FC, type ReactNode, useContext } from "react";
2025-08-04 17:45:44 +02:00
import type { ChatsChatid } from "~/schemas/public/Chats";
import type { UsersId } from "~/schemas/public/Users";
2025-11-20 16:48:29 +01:00
import type { UserWAnagrafica } from "~/server/controllers/user.controller";
2025-08-04 17:45:44 +02:00
import { api } from "~/utils/api";
2025-11-20 16:48:29 +01:00
type UserViewContextType = UserWAnagrafica & { chatid: ChatsChatid | null };
2025-08-04 17:45:44 +02:00
export const UserViewContext = createContext<UserViewContextType | null>(null);
export const UserViewProvider: FC<{ children: ReactNode; userId: UsersId }> = ({
2025-08-28 18:27:07 +02:00
children,
userId,
2025-08-04 17:45:44 +02:00
}) => {
2025-08-28 18:27:07 +02:00
const { data, isLoading } = api.users.getUser.useQuery({ id: userId });
const { data: chatid, isLoading: chatLoading } =
api.chat.getChatIdByUser.useQuery({ userId });
if ((!isLoading && !data) || (!chatLoading && chatid === undefined)) {
throw new Error("Utente non trovato");
}
if (!isLoading && data && !chatLoading && chatid !== undefined) {
return (
<UserViewContext.Provider value={{ ...data, chatid }}>
{children}
</UserViewContext.Provider>
);
}
return null;
2025-08-04 17:45:44 +02:00
};
2025-11-20 16:48:29 +01:00
export const useUserViewContext = () => {
const context = useContext(UserViewContext);
if (!context) {
throw new Error(
"useUserViewContext must be used within a UserViewProvider",
);
}
return context;
};