feat: Add CMS context, hooks, and types for managing CMS data
- Implemented CmsContext and CmsProvider for global state management of CMS data. - Created a custom hook `useGetCms` to fetch CMS data using React Query. - Defined TypeScript interfaces for CMS response and its related data structures. - Added error handling for data fetching in both the service and context.
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import { CmsResponse } from "@/types/TCms";
|
||||
import React, { createContext, ReactNode, useContext } from "react";
|
||||
|
||||
interface CmsContextType {
|
||||
cmsData: CmsResponse | null;
|
||||
}
|
||||
|
||||
const CmsContext = createContext<CmsContextType | undefined>(undefined);
|
||||
|
||||
interface CmsProviderProps {
|
||||
children: ReactNode;
|
||||
cmsData: CmsResponse | null;
|
||||
}
|
||||
|
||||
export const CmsProvider: React.FC<CmsProviderProps> = ({
|
||||
children,
|
||||
cmsData,
|
||||
}) => {
|
||||
return (
|
||||
<CmsContext.Provider value={{ cmsData }}>{children}</CmsContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useCms = (): CmsContextType => {
|
||||
const context = useContext(CmsContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useCms must be used within a CmsProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export async function fetchCmsData(
|
||||
id: string,
|
||||
cmsService: { getCms: (id: string) => Promise<CmsResponse> }
|
||||
): Promise<CmsResponse | null> {
|
||||
try {
|
||||
const cmsData = await cmsService.getCms(id);
|
||||
return cmsData;
|
||||
} catch (error) {
|
||||
console.error("Error fetching CMS data:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user