UNPKG

ra-core

Version:

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

75 lines 2.97 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useReferenceOneFieldController = void 0; const get_js_1 = __importDefault(require("lodash/get.js")); const record_1 = require("../record/index.cjs"); const dataProvider_1 = require("../../dataProvider/index.cjs"); const notification_1 = require("../../notification/index.cjs"); /** * Fetch a reference record in a one-to-one relationship, and return it when available * * The reference prop should be the name of one of the <Resource> components * added as <Admin> child. * * @example * * const { data, isPending, error } = useReferenceOneFieldController({ * record: { id: 7, name: 'James Joyce'} * reference: 'bios', * target: 'author_id', * }); * * @typedef {Object} UseReferenceOneFieldControllerParams * @prop {Object} props.record The current resource record * @prop {string} props.reference The linked resource name * @prop {string} props.target The target resource key * @prop {string} props.source The key current record identifier ('id' by default) * @prop {Object} props.sort The sort to apply to the referenced records * @prop {Object} props.filter The filter to apply to the referenced records * @returns {UseReferenceResult} The request state. Destructure as { referenceRecord, isPending, error }. */ const useReferenceOneFieldController = (props) => { const { reference, target, source = 'id', sort = { field: 'id', order: 'ASC' }, filter = {}, queryOptions = {}, } = props; const record = (0, record_1.useRecordContext)(props); const notify = (0, notification_1.useNotify)(); const { meta, ...otherQueryOptions } = queryOptions; const { data, error, isFetching, isLoading, isPaused, isPending, isPlaceholderData, refetch, } = (0, dataProvider_1.useGetManyReference)(reference, { target, id: (0, get_js_1.default)(record, source), pagination: { page: 1, perPage: 1 }, sort, filter, meta, }, { enabled: !!record, onError: error => notify(typeof error === 'string' ? error : error.message || 'ra.notification.http_error', { type: 'error', messageArgs: { _: typeof error === 'string' ? error : error?.message ? error.message : undefined, }, }), ...otherQueryOptions, }); return { referenceRecord: data ? data[0] : undefined, error, isFetching, isLoading, isPaused, isPending, isPlaceholderData, refetch, }; }; exports.useReferenceOneFieldController = useReferenceOneFieldController; //# sourceMappingURL=useReferenceOneFieldController.js.map