31 lines
1.1 KiB
TypeScript
31 lines
1.1 KiB
TypeScript
|
|
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;
|
||
|
|
};
|