infoalloggi-monorepo/apps/infoalloggi/src/providers/ServizioProvider.tsx

76 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-08-04 17:45:44 +02:00
import { createContext, useContext } from "react";
import type { AnnunciId } from "~/schemas/public/Annunci";
import type { ServizioServizioId } from "~/schemas/public/Servizio";
import type { UsersId } from "~/schemas/public/Users";
import type { ServizioData } from "~/server/controllers/servizio.controller";
type ServizioContextProps = {
isAdmin: boolean;
userId: UsersId;
servizioId: ServizioServizioId;
servizio: ServizioData;
};
const ServizioContext = createContext<ServizioContextProps | null>(null);
export const ServizioProvider = ({
isAdmin,
userId,
servizioId,
servizio,
children,
}: {
isAdmin: boolean;
userId: UsersId;
servizioId: ServizioServizioId;
servizio: ServizioData;
children: React.ReactNode;
}) => {
return (
<ServizioContext.Provider value={{ isAdmin, userId, servizioId, servizio }}>
{children}
</ServizioContext.Provider>
);
};
export const useServizio = () => {
const servizioContext = useContext(ServizioContext);
if (!servizioContext) {
throw new Error("useServizio must be used within a ServizioProvider");
}
return servizioContext;
};
type ServizioAnnuncioContextProps = {
data: ServizioData["annunci"][number];
annuncioId: AnnunciId;
};
const ServizioAnnuncioContext =
createContext<ServizioAnnuncioContextProps | null>(null);
export const ServizioAnnuncioProvider = ({
data,
children,
}: {
data: ServizioData["annunci"][number];
children: React.ReactNode;
}) => {
return (
<ServizioAnnuncioContext.Provider
value={{ data, annuncioId: data.annunci_id }}
>
{children}
</ServizioAnnuncioContext.Provider>
);
};
export const useServizioAnnuncio = () => {
const servizioAnnuncioContext = useContext(ServizioAnnuncioContext);
if (!servizioAnnuncioContext) {
throw new Error(
"useServizioAnnuncio must be used within a ServizioAnnuncioProvider",
);
}
return servizioAnnuncioContext;
};