mirror of
https://github.com/fosrl/pangolin.git
synced 2026-05-11 06:44:13 +00:00
🚧 wip: update resource policy form
This commit is contained in:
63
src/providers/ResourcePolicyProvider.tsx
Normal file
63
src/providers/ResourcePolicyProvider.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { GetResourcePolicyResponse } from "@server/routers/policy";
|
||||
|
||||
interface ResourcePolicyProviderProps {
|
||||
children: React.ReactNode;
|
||||
policy: GetResourcePolicyResponse;
|
||||
}
|
||||
|
||||
export function ResourcePolicyProvider({
|
||||
children,
|
||||
policy: serverPolicy
|
||||
}: ResourcePolicyProviderProps) {
|
||||
const [policy, setPolicy] =
|
||||
useState<GetResourcePolicyResponse>(serverPolicy);
|
||||
|
||||
const t = useTranslations();
|
||||
|
||||
const updatePolicy = (
|
||||
updatedPolicy: Partial<GetResourcePolicyResponse>
|
||||
) => {
|
||||
if (!policy) {
|
||||
throw new Error(t("resourceErrorNoUpdate"));
|
||||
}
|
||||
|
||||
setPolicy((prev) => {
|
||||
if (!prev) {
|
||||
return prev;
|
||||
}
|
||||
|
||||
return {
|
||||
...prev,
|
||||
...updatedPolicy
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<ResourcePolicyContext value={{ ...policy, updatePolicy }}>
|
||||
{children}
|
||||
</ResourcePolicyContext>
|
||||
);
|
||||
}
|
||||
|
||||
export type ResourcePolicyContextType = GetResourcePolicyResponse & {
|
||||
updatePolicy: (updatedPolicy: Partial<GetResourcePolicyResponse>) => void;
|
||||
};
|
||||
|
||||
export const ResourcePolicyContext = createContext<
|
||||
ResourcePolicyContextType | undefined
|
||||
>(undefined);
|
||||
|
||||
export function useResourcePolicyContext() {
|
||||
const context = useContext(ResourcePolicyContext);
|
||||
if (context === undefined) {
|
||||
throw new Error(
|
||||
"useResourcePolicyContext must be used within a ResourcePolicyProvider"
|
||||
);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user