UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

207 lines 8.18 kB
import { useCallback } from 'react'; import { useAuthenticated, useRequireAccess } from "../../auth/index.js"; import { useRedirect, useParams } from "../../routing/index.js"; import { useNotify } from "../../notification/index.js"; import { useGetOne, useUpdate, } from "../../dataProvider/index.js"; import { useTranslate } from "../../i18n/index.js"; import { useResourceContext, useGetResourceLabel, useGetRecordRepresentation, } from "../../core/index.js"; import { useMutationMiddlewares, } from "../saveContext/index.js"; /** * Prepare data for the Edit view. * * useEditController does a few things: * - it grabs the id from the URL and the resource name from the ResourceContext, * - it fetches the record via useGetOne, * - it prepares the page title. * * @param {Object} props The props passed to the Edit component. * * @return {Object} controllerProps Fetched data and callbacks for the Edit view * * @example * * import { useEditController } from 'react-admin'; * import EditView from './EditView'; * * const MyEdit = () => { * const controllerProps = useEditController({ resource: 'posts', id: 123 }); * return <EditView {...controllerProps} {...props} />; * } */ export const useEditController = (props = {}) => { const { disableAuthentication = false, id: propsId, mutationMode = 'undoable', mutationOptions = {}, queryOptions = {}, redirect: redirectTo = DefaultRedirect, redirectOnError = DefaultRedirectOnError, transform, } = props; const resource = useResourceContext(props); if (!resource) { throw new Error('useEditController requires a non-empty resource prop or context'); } const { isPending: isPendingAuthenticated } = useAuthenticated({ enabled: !disableAuthentication, }); const { isPending: isPendingCanAccess } = useRequireAccess({ action: 'edit', resource, enabled: !disableAuthentication && !isPendingAuthenticated, }); const getRecordRepresentation = useGetRecordRepresentation(resource); const translate = useTranslate(); const notify = useNotify(); const redirect = useRedirect(); const { id: routeId } = useParams(); if (!routeId && !propsId) { throw new Error('useEditController requires an id prop or a route with an /:id? parameter.'); } const id = propsId ?? routeId; const { meta: queryMeta, ...otherQueryOptions } = queryOptions; const { meta: mutationMeta, onSuccess, onError, ...otherMutationOptions } = mutationOptions; if ((queryMeta || mutationMeta) && JSON.stringify(queryMeta) !== JSON.stringify(mutationMeta) && redirectTo === false) { console.warn('When not redirecting after editing, query meta and mutation meta should be the same, or you will have data update issues.'); } const { registerMutationMiddleware, getMutateWithMiddlewares, unregisterMutationMiddleware, } = useMutationMiddlewares(); const { data: record, error, isLoading, isFetching, isPaused, isPending, isPlaceholderData, refetch, } = useGetOne(resource, { id, meta: queryMeta }, { enabled: (!isPendingAuthenticated && !isPendingCanAccess) || disableAuthentication, onError: () => { notify('ra.notification.item_doesnt_exist', { type: 'error', }); redirect(redirectOnError, resource, id); }, refetchOnReconnect: false, refetchOnWindowFocus: false, retry: false, ...otherQueryOptions, }); // eslint-disable-next-line eqeqeq if (record && record.id && record.id != id) { throw new Error(`useEditController: Fetched record's id attribute (${record.id}) must match the requested 'id' (${id})`); } const getResourceLabel = useGetResourceLabel(); const recordRepresentation = getRecordRepresentation(record); const defaultTitle = translate(`resources.${resource}.page.edit`, { id, record, recordRepresentation: typeof recordRepresentation === 'string' ? recordRepresentation : '', _: translate('ra.page.edit', { name: getResourceLabel(resource, 1), id, record, recordRepresentation: typeof recordRepresentation === 'string' ? recordRepresentation : '', }), }); const recordCached = { id, previousData: record }; const [update, { isPending: saving }] = useUpdate(resource, recordCached, { onSuccess: async (...args) => { if (onSuccess) { return onSuccess(...args); } const [data] = args; notify(`resources.${resource}.notifications.updated`, { type: 'info', messageArgs: { smart_count: 1, _: translate('ra.notification.updated', { smart_count: 1, }), }, undoable: mutationMode === 'undoable', }); redirect(redirectTo, resource, data.id, data); }, onError: (...args) => { if (onError) { return onError(...args); } const [error] = args; // Don't trigger a notification if this is a validation error // (notification will be handled by the useNotifyIsFormInvalid hook) const validationErrors = error?.body?.errors; const hasValidationErrors = !!validationErrors && Object.keys(validationErrors).length > 0; if (!hasValidationErrors || mutationMode !== 'pessimistic') { notify(typeof error === 'string' ? error : error.message || 'ra.notification.http_error', { type: 'error', messageArgs: { _: typeof error === 'string' ? error : error instanceof Error || (typeof error === 'object' && error !== null && error.hasOwnProperty('message')) ? // @ts-ignore error.message : undefined, }, }); } }, ...otherMutationOptions, mutationMode, returnPromise: mutationMode === 'pessimistic', getMutateWithMiddlewares, }); const save = useCallback((data, { onSuccess: onSuccessFromSave, onError: onErrorFromSave, transform: transformFromSave, meta: metaFromSave, } = {}) => Promise.resolve(transformFromSave ? transformFromSave(data, { previousData: recordCached.previousData, }) : transform ? transform(data, { previousData: recordCached.previousData, }) : data).then(async (data) => { try { await update(resource, { id, data, meta: metaFromSave ?? mutationMeta, previousData: record, }, { onError: onErrorFromSave, onSuccess: onSuccessFromSave, }); } catch (error) { if (error.body?.errors != null) { return error.body.errors; } } }), [ id, mutationMeta, record, resource, transform, update, recordCached.previousData, ]); return { defaultTitle, error, isFetching, isLoading, isPaused, isPending, isPlaceholderData, mutationMode, record, redirect: redirectTo, redirectOnError, refetch, registerMutationMiddleware, resource, save, saving, unregisterMutationMiddleware, }; }; const DefaultRedirect = 'list'; const DefaultRedirectOnError = 'list'; //# sourceMappingURL=useEditController.js.map