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

31 lines
1.1 KiB
TypeScript
Raw Normal View History

2025-08-04 17:45:44 +02:00
import { createContext, type FC, type ReactNode } from "react";
import type { ChatsChatid } from "~/schemas/public/Chats";
import type { UsersId } from "~/schemas/public/Users";
import type { getUserReturnType } from "~/server/controllers/user.controller";
import { api } from "~/utils/api";
type UserViewContextType = getUserReturnType & { chatid: ChatsChatid | null };
export const UserViewContext = createContext<UserViewContextType | null>(null);
export const UserViewProvider: FC<{ children: ReactNode; userId: UsersId }> = ({
children,
userId,
}) => {
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;
};