47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import { Chantier } from "@/class/class";
|
|
import { createContext, ReactNode, useContext, useMemo, useState } from "react";
|
|
import { getChantiers } from "@/services/ressourcesService";
|
|
|
|
type ChantierContextType = {
|
|
chantier: Chantier | null;
|
|
setChantier: (p: Chantier | null) => void;
|
|
syncChantier: () => Promise<void>;
|
|
};
|
|
|
|
const ChantierContext = createContext<ChantierContextType | null>(null);
|
|
|
|
type ChantierProviderProps = {
|
|
children: ReactNode;
|
|
};
|
|
|
|
export const ChantierProvider = ({ children }: ChantierProviderProps) => {
|
|
const [chantier, setChantier] = useState<Chantier | null>(null);
|
|
|
|
const syncChantier = async () => {
|
|
if (!chantier) return;
|
|
|
|
const all = await getChantiers();
|
|
const updated = all.find(c => c.id === chantier.id);
|
|
|
|
if (updated) {
|
|
setChantier(updated);
|
|
}
|
|
};
|
|
|
|
const value = useMemo(() => ({ chantier, setChantier,syncChantier }), [chantier]);
|
|
|
|
return (
|
|
<ChantierContext.Provider value={value}>
|
|
{children}
|
|
</ChantierContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useChantier = () => {
|
|
const context = useContext(ChantierContext);
|
|
if (!context) {
|
|
throw new Error("useChantier doit être utilisé dans <ChantierProvider>");
|
|
}
|
|
return context;
|
|
};
|