UNPKG

ra-core

Version:

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

67 lines 3.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useChoicesContext = void 0; const react_1 = require("react"); const controller_1 = require("../../controller/index.cjs"); const ChoicesContext_1 = require("./ChoicesContext.cjs"); const useChoicesContext = (options = {}) => { const context = (0, react_1.useContext)(ChoicesContext_1.ChoicesContext); const choices = options.choices && isArrayOfStrings(options.choices) ? convertOptionsToChoices(options.choices) : options.choices; // @ts-ignore cannot satisfy the type of useList because of ability to pass partial options const { data, ...list } = (0, controller_1.useList)({ data: choices, isLoading: options.isLoading ?? false, isPending: options.isPending ?? false, isFetching: options.isFetching ?? false, error: options.error, // When not in a ChoicesContext, paginating does not make sense (e.g. AutocompleteInput). perPage: Infinity, }); const result = (0, react_1.useMemo)(() => { // Props take precedence over context. if (options.choices || !context) { return { allChoices: data, availableChoices: options.availableChoices ?? data, selectedChoices: options.selectedChoices ?? data, displayedFilters: options.selectedChoices ?? list.displayedFilters, error: options.error, filter: options.filter ?? list.filter, filterValues: options.filterValues ?? list.filterValues, hasNextPage: options.hasNextPage ?? list.hasNextPage, hasPreviousPage: options.hasPreviousPage ?? list.hasPreviousPage, hideFilter: options.hideFilter ?? list.hideFilter, isFetching: list.isFetching ?? false, // we must take the one for useList, otherwise the loading state isn't synchronized with the data isLoading: list.isLoading ?? false, // same isPaused: list.isPaused ?? false, // same isPending: list.isPending ?? false, // same isPlaceholderData: list.isPlaceholderData ?? false, // same page: options.page ?? list.page, perPage: options.perPage ?? list.perPage, refetch: options.refetch ?? list.refetch, resource: options.resource ?? list.resource, setFilters: options.setFilters ?? list.setFilters, setPage: options.setPage ?? list.setPage, setPerPage: options.setPerPage ?? list.setPerPage, setSort: options.setSort ?? list.setSort, showFilter: options.showFilter ?? list.showFilter, sort: options.sort ?? list.sort, source: options.source, total: options.total ?? list.total, isFromReference: false, }; } return context; }, [context, data, list, options]); return result; }; exports.useChoicesContext = useChoicesContext; const isArrayOfStrings = (choices) => Array.isArray(choices) && choices.every(choice => typeof choice === 'string'); const convertOptionsToChoices = (options) => options.map(choice => ({ id: choice, name: choice, })); //# sourceMappingURL=useChoicesContext.js.map