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

76 lines
1.8 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 = {
2025-08-28 18:27:07 +02:00
isAdmin: boolean;
userId: UsersId;
servizioId: ServizioServizioId;
servizio: ServizioData;
2025-08-04 17:45:44 +02:00
};
const ServizioContext = createContext<ServizioContextProps | null>(null);
export const ServizioProvider = ({
2025-08-28 18:27:07 +02:00
isAdmin,
userId,
servizioId,
servizio,
children,
2025-08-04 17:45:44 +02:00
}: {
2025-08-28 18:27:07 +02:00
isAdmin: boolean;
userId: UsersId;
servizioId: ServizioServizioId;
servizio: ServizioData;
children: React.ReactNode;
2025-08-04 17:45:44 +02:00
}) => {
2025-08-28 18:27:07 +02:00
return (
<ServizioContext.Provider value={{ isAdmin, userId, servizioId, servizio }}>
{children}
</ServizioContext.Provider>
);
2025-08-04 17:45:44 +02:00
};
export const useServizio = () => {
2025-08-28 18:27:07 +02:00
const servizioContext = useContext(ServizioContext);
if (!servizioContext) {
throw new Error("useServizio must be used within a ServizioProvider");
}
return servizioContext;
2025-08-04 17:45:44 +02:00
};
type ServizioAnnuncioContextProps = {
2025-08-28 18:27:07 +02:00
data: ServizioData["annunci"][number];
annuncioId: AnnunciId;
2025-08-04 17:45:44 +02:00
};
const ServizioAnnuncioContext =
2025-08-28 18:27:07 +02:00
createContext<ServizioAnnuncioContextProps | null>(null);
2025-08-04 17:45:44 +02:00
export const ServizioAnnuncioProvider = ({
2025-08-28 18:27:07 +02:00
data,
children,
2025-08-04 17:45:44 +02:00
}: {
2025-08-28 18:27:07 +02:00
data: ServizioData["annunci"][number];
children: React.ReactNode;
2025-08-04 17:45:44 +02:00
}) => {
2025-08-28 18:27:07 +02:00
return (
<ServizioAnnuncioContext.Provider
value={{ data, annuncioId: data.annunci_id }}
>
{children}
</ServizioAnnuncioContext.Provider>
);
2025-08-04 17:45:44 +02:00
};
export const useServizioAnnuncio = () => {
2025-08-28 18:27:07 +02:00
const servizioAnnuncioContext = useContext(ServizioAnnuncioContext);
if (!servizioAnnuncioContext) {
throw new Error(
"useServizioAnnuncio must be used within a ServizioAnnuncioProvider",
);
}
return servizioAnnuncioContext;
2025-08-04 17:45:44 +02:00
};