UNPKG

@premieroctet/next-admin

Version:

Next-Admin provides a customizable and turnkey admin dashboard for applications built with Next.js and powered by the Prisma ORM. It aims to simplify the development process by providing a turnkey admin system that can be easily integrated into your proje

51 lines (50 loc) 2 kB
import { useConfig } from "../context/ConfigContext.mjs"; import { useI18n } from "../context/I18nContext.mjs"; import { useMessage } from "../context/MessageContext.mjs"; import { useRouterInternal } from "./useRouterInternal.mjs"; const SPECIFIC_IDS_TO_RUN_ACTION = { DELETE: "__admin-delete" }; const useAction = (resource, ids)=>{ const { t } = useI18n(); const { apiBasePath } = useConfig(); const { showMessage } = useMessage(); const { router } = useRouterInternal(); const runAction = async (modelAction)=>{ try { if (Object.values(SPECIFIC_IDS_TO_RUN_ACTION).includes(modelAction.id) && "action" in modelAction) await modelAction.action(ids); else { const response = await fetch(`${apiBasePath}/${resource}/actions/${modelAction.id}`, { method: "POST", body: JSON.stringify(ids), headers: { "Content-Type": "application/json" } }); router.refresh(); const actionMessage = await response.json(); if (actionMessage && actionMessage.message) return void showMessage({ type: actionMessage.type, message: t(actionMessage.message), component: modelAction.component }); if (!response.ok) throw new Error(); } if (modelAction.successMessage) showMessage({ type: "success", message: t(modelAction.successMessage), component: modelAction.component }); } catch { if (modelAction.errorMessage) showMessage({ type: "error", message: t(modelAction.errorMessage), component: modelAction.component }); } }; return { runAction }; }; export { SPECIFIC_IDS_TO_RUN_ACTION, useAction };