ra-core
- Version 5.13.3
- Published
- 7.34 MB
- 8 dependencies
- MIT license
Install
npm i ra-coreyarn add ra-corepnpm add ra-coreOverview
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
Index
Variables
- ArrayInputContext
- AUTH_CHECK
- AUTH_ERROR
- AUTH_GET_PERMISSIONS
- AUTH_LOGIN
- AUTH_LOGOUT
- choices
- ChoicesContext
- CloseNotificationContext
- convertLegacyAuthProvider
- CREATE
- DataProviderContext
- DataTableCallbacksContext
- DataTableColumnFilterContext
- DataTableColumnRankContext
- DataTableConfigContext
- DataTableDataContext
- DataTableRenderContext
- DataTableSelectedIdsContext
- DataTableSortContext
- DataTableStoreContext
- DEFAULT_LOCALE
- defaultDataProvider
- DefaultTitleContext
- DefaultTitleContextProvider
- DELETE
- DELETE_MANY
- escapePath
- ExporterContext
- fetchActionsWithArrayOfIdentifiedRecordsResponse
- fetchActionsWithArrayOfRecordsResponse
- fetchActionsWithRecordResponse
- fetchActionsWithTotalResponse
- FormGroupContext
- GET_LIST
- GET_MANY
- GET_MANY_REFERENCE
- GET_ONE
- getElementsFromRecords
- getValuesFromRecords
- HasDashboardContext
- HasDashboardContextProvider
- HIDE_FILTER
- I18N_CHANGE_LOCALE
- I18N_TRANSLATE
- I18nContext
- InferenceTypes
- InfinitePaginationContext
- injectedProps
- maxLength
- maxValue
- minLength
- minValue
- NotificationContext
- number
- PreviousLocationStorageKey
- reactAdminFetchActions
- REFERENCES_STATUS_EMPTY
- REFERENCES_STATUS_INCOMPLETE
- REFERENCES_STATUS_READY
- regex
- required
- ResourceContext
- SaveContext
- SET_FILTER
- SET_PAGE
- SET_PER_PAGE
- SET_SORT
- SHOW_FILTER
- SimpleFormIteratorContext
- SimpleFormIteratorItemContext
- SORT_ASC
- SORT_DESC
- TranslatableContext
- undoableEventEmitter
- UPDATE
- UPDATE_MANY
- useFilterState
- usePaginationState
- UserMenuContext
- warning
Functions
- addRefreshAuthToAuthProvider()
- addRefreshAuthToDataProvider()
- applyCallbacks()
- asyncDebounce()
- checkHasDirtyFields()
- combine2Validators()
- combineDataProviders()
- composeSyncValidators()
- composeValidators()
- convertLegacyDataProvider()
- defaultExporter()
- downloadCSV()
- fetchRelatedRecords()
- getFieldLabelTranslationArgs()
- getFormGroupState()
- getListControllerProps()
- getMutationMode()
- getNumberOrDefault()
- getQuery()
- getRecordForLocale()
- getRecordFromLocation()
- getResourceFieldLabelKey()
- getSelectedReferencesStatus()
- getSimpleValidationResolver()
- getStatusForArrayInput()
- getStatusForInput()
- getStorage()
- getSuggestionsFactory()
- hasCustomParams()
- inferTypeFromValues()
- isEmpty()
- isRequired()
- localStorageStore()
- LogoutOnMount()
- mergeRefs()
- mergeTranslations()
- parseQueryFromLocation()
- queryReducer()
- removeDoubleSlashes()
- removeEmpty()
- removeKey()
- resolveBrowserLocale()
- sanitizeFetchType()
- sanitizeFieldRestProps()
- sanitizeInputRestProps()
- sanitizeListRestProps()
- setSubmissionErrors()
- shallowEqual()
- substituteTokens()
- testDataProvider()
- useApplyInputDefaultValues()
- useArrayInput()
- useAugmentedForm()
- useAuthenticated()
- useAuthProvider()
- useAuthState()
- useBasename()
- useBulkDeleteController()
- useBulkExport()
- useCanAccess()
- useCanAccessCallback()
- useCanAccessResources()
- useCheckAuth()
- useCheckForApplicationUpdate()
- useChoicesContext()
- useCloseNotification()
- useCreate()
- useCreateController()
- useCreatePath()
- useDataProvider()
- useDataTableCallbacksContext()
- useDataTableColumnFilterContext()
- useDataTableColumnRankContext()
- useDataTableConfigContext()
- useDataTableDataContext()
- useDataTableRenderContext()
- useDataTableSelectedIdsContext()
- useDataTableSortContext()
- useDataTableStoreContext()
- useDebouncedEvent()
- useDeepCompareEffect()
- useDefaultTitle()
- useDelete()
- useDeleteMany()
- useEditController()
- useEvent()
- useFieldValue()
- useFilterContext()
- useFormGroup()
- useFormGroupContext()
- useFormGroups()
- useFormIsDirty()
- useGetArrayInputNewItemDefaults()
- useGetIdentity()
- useGetList()
- useGetMany()
- useGetManyAggregate()
- useGetManyReference()
- useGetOne()
- useGetPathForRecord()
- useGetPathForRecordCallback()
- useGetPermissions()
- useGetRecordId()
- useGetRecordRepresentation()
- useGetResourceLabel()
- useGetValidationErrorMessage()
- useHandleAuthCallback()
- useHasDashboard()
- useI18nProvider()
- useInfiniteGetList()
- useInfiniteListController()
- useInfinitePaginationContext()
- useInput()
- useIsAuthPending()
- useIsDataLoaded()
- useIsMounted()
- useIsOffline()
- useList()
- useListContext()
- useListContextWithProps()
- useListController()
- useListFilterContext()
- useListPaginationContext()
- useListParams()
- useListSortContext()
- useLoading()
- useLocales()
- useLogin()
- useLogout()
- useLogoutIfAccessDenied()
- useMutationMiddlewares()
- useMutationWithMutationMode()
- useNotificationContext()
- useNotify()
- useNotifyIsFormInvalid()
- usePermissions()
- usePickSaveContext()
- usePreference()
- usePreferenceInput()
- usePreferencesEditor()
- usePrevious()
- usePrevNextController()
- useRecordContext()
- useRecordFromLocation()
- useRecordSelection()
- useRedirect()
- useReference()
- useReferenceArrayFieldController()
- useReferenceArrayInputController()
- useReferenceFieldController()
- useReferenceInputController()
- useReferenceManyFieldController()
- useRefresh()
- useRegisterMutationMiddleware()
- useRemoveFromStore()
- useRemoveItemsFromStore()
- useResetErrorBoundaryOnLocationChange()
- useResetStore()
- useResourceContext()
- useResourceDefinition()
- useResourceDefinitionContext()
- useResourceDefinitions()
- useResourceTranslation()
- useRestoreScrollPosition()
- useSafeSetState()
- useSaveContext()
- useSetInspectorTitle()
- useShowController()
- useSimpleFormIterator()
- useSimpleFormIteratorItem()
- useSortState()
- useSplatPathBase()
- useStore()
- useStoreContext()
- useSuggestions()
- useTimeout()
- useTrackScrollPosition()
- useTranslatable()
- useTranslatableContext()
- useTranslate()
- useTranslateLabel()
- useUnique()
- useUnselect()
- useUnselectAll()
- useUpdate()
- useUpdateMany()
- useUserMenu()
- useWhyDidYouUpdate()
- useWrappedSource()
- WarnWhenUnsavedChanges()
- withLifecycleCallbacks()
Classes
Interfaces
Type Aliases
- AdminChildren
- AnyString
- ArrayInputContextValue
- AuthActionType
- AuthProvider
- AuthRedirectResult
- CatchAllComponent
- CheckAuth
- ChoicesContextBaseValue
- ChoicesContextValue
- CloseNotificationContextValue
- CreateMutationFunction
- CreatePathType
- DashboardComponent
- DataProvider
- DataProviderMatcher
- DataProviderResult
- DataTableDataContextProps
- Dispatch
- EditControllerResult
- Exporter
- ExtractRecordPaths
- FetchRelatedRecords
- FormFunctions
- FormGroupContextValue
- GetRecordForLocale
- GetResourceLabel
- GetValidationMessage
- HintedString
- I18nContextProps
- I18nProvider
- Identifier
- InfiniteListControllerResult
- InfinitePaginationContextValue
- InputProps
- LayoutComponent
- LegacyAuthProvider
- LegacyDataProvider
- LinkToFunctionType
- LinkToType
- ListControllerResult
- LoadingComponent
- Locale
- LoginComponent
- Middleware
- MutationFunctionWithOptions
- MutationMode
- NotificationContextType
- NotificationType
- OnError
- OnSuccess
- PossibleInferredElementTypes
- RecordPath
- RecordToStringFunction
- RecordValues
- RedirectionSideEffect
- RenderContextType
- RenderResourcesFunction
- ResourceCallback
- ResourceCallbacks
- ResourceCallbacksValue
- ResourceContextValue
- ResourceElement
- RowClickFunctionBase
- SaveHandler
- SaveHandlerCallbacks
- SelectTranslatableLocale
- SetOnSave
- ShowControllerResult
- SimpleFormIteratorContextValue
- SimpleFormIteratorItemContextValue
- Snapshot
- TitleComponent
- TransformData
- TranslateFunction
- UndoableMutation
- UpdateMutationFunction
- UseAugmentedFormProps
- UseAuthenticatedOptions
- UseBulkExportResult
- UseCanAccessCallback
- UseCanAccessCallbackOptions
- UseCanAccessCallbackResult
- UseCanAccessResourcesResult
- UseCanAccessResult
- UseCreateOptions
- UseCreateResult
- UseDeleteManyOptions
- UseDeleteManyResult
- UseDeleteOptions
- UseDeleteResult
- UseGetIdentityResult
- UseGetListHookValue
- UseGetListOptions
- UseGetManyAggregateOptions
- UseGetManyHookValue
- UseGetManyOptions
- UseGetManyReferenceHookOptions
- UseGetManyReferenceHookValue
- UseGetOneHookValue
- UseGetOneOptions
- UseGetRouteForRecordOptions
- UseHandleAuthCallbackOptions
- UseInfiniteGetListHookValue
- UseInfiniteGetListOptions
- UseInputValue
- UseIsAuthPendingParams
- UseListValue
- UseMutationWithMutationModeOptions
- UseMutationWithMutationModeResult
- UsePrevNextControllerResult
- UserCheck
- UseRecordFromLocationOptions
- UseRecordSelectionArgs
- UseRecordSelectionResult
- UserMenuContextValue
- useStoreResult
- UseTranslatableOptions
- UseUniqueOptions
- UseUpdateManyOptions
- UseUpdateManyResult
- UseUpdateOptions
- UseUpdateResult
- ValidateForm
- ValidationErrorMessage
- Validator
- ValidUntil
Namespaces
Variables
variable ArrayInputContext
const ArrayInputContext: any;A React context that provides access to an ArrayInput methods as provided by react-hook-form Useful to create custom array input iterators.
See Also
{ArrayInput}
variable AUTH_CHECK
const AUTH_CHECK: string;variable AUTH_ERROR
const AUTH_ERROR: string;variable AUTH_GET_PERMISSIONS
const AUTH_GET_PERMISSIONS: string;variable AUTH_LOGIN
const AUTH_LOGIN: string;variable AUTH_LOGOUT
const AUTH_LOGOUT: string;variable choices
const choices: ( list: any, message?: any) => (value: any, values: any) => string | { message: string; args: any };Choices validator
Returns an error if the value is not among the list passed as parameter
Parameter list
Parameter message
Example 1
const genderValidators = [choices(['male', 'female'], 'Must be either Male or Female')]; <TextInput name="gender" validate={genderValidators} />
variable ChoicesContext
const ChoicesContext: any;Context to store choices and functions to retrieve them.
Use the useChoicesContext() hook to read the context.
variable CloseNotificationContext
const CloseNotificationContext: any;variable convertLegacyAuthProvider
const convertLegacyAuthProvider: ( legacyAuthProvider: LegacyAuthProvider) => AuthProvider;Turn a function-based authProvider to an object-based one
Allows using legacy authProviders transparently.
Parameter legacyAuthProvider
A legacy authProvider (type, params) => Promise
Returns
{Object} An authProvider that react-admin can use
variable CREATE
const CREATE: string;variable DataProviderContext
const DataProviderContext: any;variable DataTableCallbacksContext
const DataTableCallbacksContext: any;variable DataTableColumnFilterContext
const DataTableColumnFilterContext: any;variable DataTableColumnRankContext
const DataTableColumnRankContext: any;variable DataTableConfigContext
const DataTableConfigContext: any;variable DataTableDataContext
const DataTableDataContext: any;variable DataTableRenderContext
const DataTableRenderContext: any;variable DataTableSelectedIdsContext
const DataTableSelectedIdsContext: any;variable DataTableSortContext
const DataTableSortContext: any;variable DataTableStoreContext
const DataTableStoreContext: any;variable DEFAULT_LOCALE
const DEFAULT_LOCALE: string;variable defaultDataProvider
const defaultDataProvider: DataProvider<string>;variable DefaultTitleContext
const DefaultTitleContext: any;variable DefaultTitleContextProvider
const DefaultTitleContextProvider: any;variable DELETE
const DELETE: string;variable DELETE_MANY
const DELETE_MANY: string;variable email
const email: (message?: any) => any;Email validator
Returns an error if the value is not a valid email
Parameter message
Example 1
const emailValidators = [email('Must be an email')]; <TextInput name="email" validate={emailValidators} />
variable escapePath
const escapePath: (url: any) => any;Escape special characters in path so that react-router Route does not do any special treatment
Example 1
escapePath('/foo(bar)') => 'foo(bar)'
See Also
https://github.com/ReactTraining/react-router/blob/v3/docs/guides/RouteMatching.md#path-syntax
variable ExporterContext
const ExporterContext: any;variable fetchActionsWithArrayOfIdentifiedRecordsResponse
const fetchActionsWithArrayOfIdentifiedRecordsResponse: string[];variable fetchActionsWithArrayOfRecordsResponse
const fetchActionsWithArrayOfRecordsResponse: string[];variable fetchActionsWithRecordResponse
const fetchActionsWithRecordResponse: string[];variable fetchActionsWithTotalResponse
const fetchActionsWithTotalResponse: string[];variable FormGroupContext
const FormGroupContext: any;Context allowing inputs to register to a specific group. This enables other components in the group to access group properties such as its validation (valid/invalid) or whether its inputs have been updated (dirty/pristine).
This should only be used through a FormGroupContextProvider.
variable GET_LIST
const GET_LIST: string;variable GET_MANY
const GET_MANY: string;variable GET_MANY_REFERENCE
const GET_MANY_REFERENCE: string;variable GET_ONE
const GET_ONE: string;variable getElementsFromRecords
const getElementsFromRecords: ( records: any[], types: InferredTypeMap) => InferredElement[];Get a list of React-admin field components from a list of records
Example 1
const records = [ { "id": 1, "title": "Lorem Ipsum", "views": 254, "user_id": 123, }, { "id": 2, "title": "Sic Dolor amet", "user_id": 456, }, ]; const types = { id: NumberField, string: TextField, number: NumberField, reference: ReferenceField }; const components = getElementsFromRecords(records, types); // [ // , // , // , // , // ];
variable getValuesFromRecords
const getValuesFromRecords: (records: any[]) => any;Gets a list of values indexed by field based on a list of records
Example 1
const records = [ { id: 1, title: "Lorem Ipsum", views: 254, user_id: 123, }, { id: 2, title: "Sic Dolor amet", views: 65, user_id: 456, }, ]; getValuesFromRecords(records); // { // id: [1, 2], // title: ['Lorem Ipsum', 'Sic Dolor amet'], // views: [254, 65], // user_id: [123, 456], // }
variable HasDashboardContext
const HasDashboardContext: any;variable HasDashboardContextProvider
const HasDashboardContextProvider: any;variable HIDE_FILTER
const HIDE_FILTER: string;variable I18N_CHANGE_LOCALE
const I18N_CHANGE_LOCALE: string;variable I18N_TRANSLATE
const I18N_TRANSLATE: string;i18nProvider types
variable I18nContext
const I18nContext: any;variable InferenceTypes
const InferenceTypes: readonly [ 'array', 'boolean', 'date', 'email', 'id', 'image', 'number', 'reference', 'referenceChild', 'referenceArray', 'referenceArrayChild', 'richText', 'string', 'url', 'object'];variable InfinitePaginationContext
const InfinitePaginationContext: any;Context to store the pagination callbacks from the useInfiniteListController() result.
Use the useInfinitePaginationContext() hook to read the pagination callbacks.
{Object} InfinitePaginationContextValue {Function} fetchNextPage a callback to fetch the next page {Function} fetchPreviousPage a callback to fetch the previous page
Example 1
import { useListController, ListPaginationContext } from 'ra-core';
const List = props => { const { fetchNextPage, fetchPreviousPage } = useInfiniteListController(props); return ( <InfinitePaginationContext.Provider value={{ fetchNextPage, fetchPreviousPage }}> ... </InfinitePaginationContext.Provider> ); };
variable injectedProps
const injectedProps: string[];variable maxLength
const maxLength: ( max: any, message?: any) => (value: any, values: any) => string | { message: string; args: any };Maximum length validator
Returns an error if the value has a length higher than the parameter
Parameter max
Parameter message
Example 1
const nameValidators = [maxLength(10, 'Should be at most 10 characters')]; <TextInput name="name" validate={nameValidators} />
variable maxValue
const maxValue: ( max: any, message?: any) => (value: any, values: any) => string | { message: string; args: any };Maximum validator
Returns an error if the value is higher than the parameter
Parameter max
Parameter message
Example 1
const fooValidators = [maxValue(10, 'Should be less than 10')]; <NumberInput name="foo" validate={fooValidators} />
variable minLength
const minLength: ( min: any, message?: any) => (value: any, values: any) => string | { message: string; args: any };Minimum length validator
Returns an error if the value has a length less than the parameter
Parameter min
Parameter message
Example 1
const passwordValidators = [minLength(10, 'Should be at least 10 characters')]; <TextInput type="password" name="password" validate={passwordValidators} />
variable minValue
const minValue: ( min: any, message?: any) => (value: any, values: any) => string | { message: string; args: any };Minimum validator
Returns an error if the value is less than the parameter
Parameter min
Parameter message
Example 1
const fooValidators = [minValue(5, 'Should be more than 5')]; <NumberInput name="foo" validate={fooValidators} />
variable NotificationContext
const NotificationContext: any;Context for the notification state and modifiers
Example 1
// display notifications import { useNotificationContext } from 'react-admin';
const App = () => { const { notifications } = useNotificationContext(); return ( {notifications.map(({ message }) => ( <li key={index}>{ message } ))} ); };
Example 2
// reset notifications import { useNotificationContext } from 'react-admin';
const ResetNotificationsButton = () => { const { resetNotifications } = useNotificationContext(); return ( <button onClick={() => resetNotifications()}>Reset notifications ); };
variable number
const number: ( message?: any) => (value: any, values: any) => string | { message: string; args: any };Number validator
Returns an error if the value is not a number
Parameter message
Example 1
const ageValidators = [number('Must be a number')]; <TextInput name="age" validate={ageValidators} />
variable PreviousLocationStorageKey
const PreviousLocationStorageKey: string;Key used to store the previous location in localStorage. Used by the useHandleAuthCallback hook to redirect the user to their previous location after a successful login.
variable reactAdminFetchActions
const reactAdminFetchActions: string[];variable REFERENCES_STATUS_EMPTY
const REFERENCES_STATUS_EMPTY: string;variable REFERENCES_STATUS_INCOMPLETE
const REFERENCES_STATUS_INCOMPLETE: string;variable REFERENCES_STATUS_READY
const REFERENCES_STATUS_READY: string;variable regex
const regex: any;Regular expression validator
Returns an error if the value does not match the pattern given as parameter
Parameter pattern
Parameter message
Example 1
const zipValidators = [regex(/^\d{5}(?:[-\s]\d{4})?$/, 'Must be a zip code')]; <TextInput name="zip" validate={zipValidators} />
variable required
const required: ( message?: any) => ((value: any, values: any) => string | { message: string; args: any }) & { isRequired: boolean;};Required validator
Returns an error if the value is null, undefined, or empty
Parameter message
Example 1
const titleValidators = [required('The title is required')]; <TextInput name="title" validate={titleValidators} />
variable ResourceContext
const ResourceContext: any;Context to store the current resource name.
Use the useResource() hook to read the context. That's what most components do in react-admin.
Example 1
import { useResourceContext, useTranslate } from 'ra-core';
const MyCustomEditTitle = props => { const name = useResourceContext(props);
return ( {translate(
${name}.name)} ); };
variable SaveContext
const SaveContext: any;variable SET_FILTER
const SET_FILTER: string;variable SET_PAGE
const SET_PAGE: string;variable SET_PER_PAGE
const SET_PER_PAGE: string;variable SET_SORT
const SET_SORT: string;variable SHOW_FILTER
const SHOW_FILTER: string;variable SimpleFormIteratorContext
const SimpleFormIteratorContext: any;A React context that provides access to a SimpleFormIterator data (the total number of items) and mutators (add, reorder and remove). Useful to create custom array input iterators.
See Also
{SimpleFormIterator}
{ArrayInput}
variable SimpleFormIteratorItemContext
const SimpleFormIteratorItemContext: any;A React context that provides access to a SimpleFormIterator item meta (its index and the total number of items) and mutators (reorder and remove this remove). Useful to create custom array input iterators.
See Also
{SimpleFormIterator}
{ArrayInput}
variable SORT_ASC
const SORT_ASC: string;variable SORT_DESC
const SORT_DESC: string;variable TranslatableContext
const TranslatableContext: any;variable undoableEventEmitter
const undoableEventEmitter: any;variable UPDATE
const UPDATE: string;variable UPDATE_MANY
const UPDATE_MANY: string;variable useFilterState
const useFilterState: ({ filterToQuery, permanentFilter, debounceTime,}: UseFilterStateOptions) => UseFilterStateProps;Hooks to provide filter state and setFilter which updates the query part of the filter
Parameter option
Parameter
{Function} option.filterToQuery Function to convert the filter string to a filter object. Defaults to v => ({ q: v }).
Parameter
{Object} option.permanentFilter Permanent filter to be merged with the filter string. Defaults to {}.
Parameter
{number} option.debounceTime Time in ms between filter updates - used to debounce the search. Defaults to 500ms.
Returns
{UseFilterStateOptions} The filter props
Example 1
const { filter, setFilter } = useFilter({ filterToQuery: v => ({ query: v }), permanentFilter: { foo: 'bar' }, debounceTime: 500, }); // filter initial value: { query: '', foo: 'bar' } // after updating filter setFilter('needle'); { query: 'needle', foo: 'bar' }
variable usePaginationState
const usePaginationState: (initialPagination?: { perPage?: number; page?: number;}) => PaginationHookResult;Hooks to provide pagination state (page and perPage)
Parameter initialPagination
the initial value per page
Returns
{PaginationHookResult} The pagination props
Example 1
const { page, setPage, perPage, setPerPage } = usePagination(initialPerPage);
variable UserMenuContext
const UserMenuContext: any;This context provides access to a function for closing the user menu.
Example 1
import { Logout, MenuItemLink, UserMenu, useUserMenu } from 'react-admin';
const ConfigurationMenu = () => { const { onClose } = useUserMenu(); return ( <MenuItemLink to="/configuration" primaryText="pos.configuration" leftIcon={} sidebarIsOpen onClick={onClose} /> ); };
export const MyUserMenu = () => ( );
variable warning
const warning: (condition: any, message: string) => void;Functions
function addRefreshAuthToAuthProvider
addRefreshAuthToAuthProvider: < AuthProviderType extends AuthProvider = AuthProvider>( provider: AuthProviderType, refreshAuth: () => Promise<void>) => AuthProviderType;A higher-order function which wraps an authProvider to handle refreshing authentication. This is useful when the authentication service supports a refresh token mechanism. The wrapped provider will call the refreshAuth function before calling the authProvider checkAuth, getIdentity and getPermissions methods.
The refreshAuth function should return a Promise that resolves when the authentication token has been refreshed. It might throw an error if the refresh failed. In this case, react-admin will handle the error as usual.
Parameter provider
An authProvider
Parameter refreshAuth
A function that refreshes the authentication token if needed and returns a Promise.
Returns
A wrapped authProvider.
Example 1
import { addRefreshAuthToAuthProvider } from 'react-admin'; import { authProvider } from './authProvider'; import { refreshAuth } from './refreshAuth';
const authProvider = addRefreshAuthToAuthProvider(authProvider, refreshAuth);
function addRefreshAuthToDataProvider
addRefreshAuthToDataProvider: < DataProviderType extends DataProvider<string> = DataProvider<string>>( provider: DataProviderType, refreshAuth: () => Promise<void>) => DataProviderType;A higher-order function which wraps a dataProvider to handle refreshing authentication. This is useful when the authentication service supports a refresh token mechanism. The wrapped provider will call the refreshAuth function before calling any dataProvider methods.
The refreshAuth function should return a Promise that resolves when the authentication token has been refreshed. It might throw an error if the refresh failed. In this case, react-admin will handle the error as usual.
Parameter provider
A dataProvider
Parameter refreshAuth
A function that refreshes the authentication token if needed and returns a Promise.
Returns
A wrapped dataProvider.
Example 1
import { addRefreshAuthToDataProvider } from 'react-admin'; import { jsonServerProvider } from 'ra-data-json-server'; import { refreshAuth } from './refreshAuth';
const dataProvider = addRefreshAuthToDataProvider(jsonServerProvider('http://localhost:3000'), refreshAuth);
function applyCallbacks
applyCallbacks: <U>({ name, params, dataProvider, handlers, resource,}: { name: string; params: U; dataProvider: DataProvider; handlers: ResourceCallbacks[]; resource: string;}) => Promise<U>;Apply callbacks to the params for the given resource and hook
Parameter dataProvider
The dataProvider
Parameter handlers
An array of ResourceCallbacks
Parameter resource
The resource name
Parameter hook
The hook name (beforeGetList, afterGetOne, etc.)
Parameter params
The params / result to pass to the callbacks
Returns
{Promise} The params / result after the callbacks have been applied
function asyncDebounce
asyncDebounce: <FunctionType extends (...args: any[]) => Promise<any>>( func: FunctionType, wait?: number) => (...args: Parameters<FunctionType>) => ReturnType<FunctionType>;A version of lodash/debounce that always returns a promise but wait for the debounced function to return to resolve it.
Parameter func
The function to debounce
Parameter wait
The debounce delay
Returns
A debounced function that returns a promise
function checkHasDirtyFields
checkHasDirtyFields: ( dirtyFields: Partial<Readonly<{ [x: string]: any }>>) => boolean;function combine2Validators
combine2Validators: (validator1: Validator, validator2: Validator) => Validator;function combineDataProviders
combineDataProviders: (dataProviderMatcher: DataProviderMatcher) => DataProvider;Combine multiple data providers into one.
Parameter dataProviderMatcher
A function that returns a data provider for a given resource.
Example 1
const dataProvider = combineDataProviders(resource => { switch(resource) { case 'posts': case 'comments': return dataProvider1; case 'users': return dataProvider2; default: throw new Error('Unknown resource'); } });
function composeSyncValidators
composeSyncValidators: ( ...validators: any[]) => ( value: any, values: any, meta: any) => ValidationErrorMessage | Promise<ValidationErrorMessage>;function composeValidators
composeValidators: (...validators: any[]) => Validator;function convertLegacyDataProvider
convertLegacyDataProvider: ( legacyDataProvider: LegacyDataProvider) => DataProvider;Turn a function-based dataProvider to an object-based one
Allows using legacy dataProviders transparently.
Parameter legacyDataProvider
A legacy dataProvider (type, resource, params) => Promise
Returns
{Object} A dataProvider that react-admin can use
function defaultExporter
defaultExporter: Exporter<any>;function downloadCSV
downloadCSV: (csv: string, filename?: string) => void;function fetchRelatedRecords
fetchRelatedRecords: (dataProvider: DataProvider) => FetchRelatedRecords;Helper function for calling the dataProvider.getMany() method, and getting a Promise for the records indexed by id in return.
Example 1
fetchRelatedRecords(dataProvider)(records, 'post_id', 'posts').then(posts => posts.map(record => ({ ...record, post_title: posts[record.post_id].title, })) );
function getFieldLabelTranslationArgs
getFieldLabelTranslationArgs: (options?: Args) => TranslationArguments;Returns an array of arguments to use with the translate function for the label of a field. The label will be computed from the resource and source props.
Usage: {translate(...getFieldLabelTranslationArgs({ label, resource, source }))}
See Also
useTranslateLabel for a ready-to-use hook
function getFormGroupState
getFormGroupState: (fieldStates: FieldState[]) => FormGroupState;Get the state of a form group
Parameter fieldStates
A map of field states from react-hook-form where the key is the field name.
Returns
{FormGroupState} The state of the group.
function getListControllerProps
getListControllerProps: (props: any) => {};Select the props injected by the useListController hook to be passed to the List children need This is an implementation of pick()
function getMutationMode
getMutationMode: (mutationMode: any, undoable: any) => any;function getNumberOrDefault
getNumberOrDefault: ( possibleNumber: string | number | undefined, defaultValue: number) => number;function getQuery
getQuery: ({ queryFromLocation, params, filterDefaultValues, sort, perPage,}: { queryFromLocation: any; params: any; filterDefaultValues: any; sort: any; perPage: any;}) => ListParams;Merge list params from 3 different sources: - the query string - the params stored in the state (from previous navigation) - the props passed to the List component (including the filter defaultValues)
function getRecordForLocale
getRecordForLocale: (record: {} | undefined, locale: string) => any;Returns a record where translatable fields have their values set to the value of the given locale. This is necessary because the fields rely on the RecordContext to get their values and have no knowledge of the locale.
Given the record { title: { en: 'title_en', fr: 'title_fr' } } and the locale 'fr', the record for the locale 'fr' will be { title: 'title_fr' }
function getRecordFromLocation
getRecordFromLocation: ( { state, search }: Location, { searchSource, stateSource }?: { searchSource?: string; stateSource?: string }) => Partial<RaRecord> | null;Get the initial record from the location, whether it comes from the location state or is serialized in the url search part.
function getResourceFieldLabelKey
getResourceFieldLabelKey: (resource: string, source: string) => string;function getSelectedReferencesStatus
getSelectedReferencesStatus: <RecordType extends RaRecord<Identifier> = any>( field: Pick<ControllerRenderProps, 'value'>, referenceRecords: RecordType[]) => | 'REFERENCES_STATUS_READY' | 'REFERENCES_STATUS_INCOMPLETE' | 'REFERENCES_STATUS_EMPTY';function getSimpleValidationResolver
getSimpleValidationResolver: ( validate: ValidateForm) => ( data: FieldValues) => Promise<{ values: FieldValues; errors: {} } | { values: {}; errors: any }>;Convert a simple validation function that returns an object matching the form shape with errors to a validation resolver compatible with react-hook-form.
Example 1
const validate = (values: any) => { if (values.username == null || values.username.trim() === '') { return { username: 'Required' }; } }
const validationResolver = getSimpleValidationResolver(validate);
const UserForm = () => ( <Form defaultValues={{ username: 'John' }} validationResolver={validationResolver} > );
function getStatusForArrayInput
getStatusForArrayInput: <RecordType extends RaRecord<Identifier> = any>({ field, matchingReferences, referenceRecords, translate,}: GetStatusForArrayInputParams<RecordType>) => { waiting: boolean; error: string; warning: string; choices: RecordType[];};function getStatusForInput
getStatusForInput: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>>({ field, matchingReferences, referenceRecord, translate,}: GetStatusForInputParams<RecordType>) => { waiting: boolean; error: string; warning: string; choices: RecordType[];};function getStorage
getStorage: () => Storage | LocalStorageShim;function getSuggestionsFactory
getSuggestionsFactory: ({ allowCreate, choices, createText, createValue, optionText, optionValue, getChoiceText, getChoiceValue, limitChoicesToValue, matchSuggestion, selectedItem, suggestionLimit,}: UseSuggestionsOptions & { getChoiceText: (choice: any) => string | ReactElement; getChoiceValue: (choice: any) => string;}) => (filter: any) => any[];Get the suggestions to display after applying a fuzzy search on the available choices
Example 1
getSuggestions({ choices: [{ id: 1, name: 'admin' }, { id: 2, name: 'publisher' }], optionText: 'name', optionValue: 'id', getSuggestionText: choice => choice[optionText], })('pub')
// Will return [{ id: 2, name: 'publisher' }] getSuggestions({ choices: [{ id: 1, name: 'admin' }, { id: 2, name: 'publisher' }], optionText: 'name', optionValue: 'id', getSuggestionText: choice => choice[optionText], })('pub')
// Will return [{ id: 2, name: 'publisher' }]
function hasCustomParams
hasCustomParams: (params: ListParams) => boolean;Check if user has already set custom sort, page, or filters for this list
User params come from the store as the params props. By default, this object is:
{ filter: {}, order: null, page: 1, perPage: null, sort: null }
To check if the user has custom params, we must compare the params to these initial values.
Parameter params
function inferTypeFromValues
inferTypeFromValues: (name: any, values?: any[]) => InferredElementDescription;Guesses an element type based on an array of values
Parameter name
Property name, e.g. 'date_of_birth'
Parameter values
an array of values from which to determine the type, e.g. [12, 34.4, 43]
Example 1
inferElementFromValues( 'address', ['2 Baker Street', '1 Downing street'], ); // { type: 'string', props: { source: 'address' } }
function isEmpty
isEmpty: (value: any) => boolean;function isRequired
isRequired: (validate: any) => boolean;Given a validator, returns a boolean indicating whether the field is required or not.
function localStorageStore
localStorageStore: (version?: string, appKey?: string) => Store;Store using localStorage, or memory storage in incognito mode
Example 1
import { localStorageStore } from 'react-admin';
const App = () => ( <Admin store={localStorageStore()}> ... );
function LogoutOnMount
LogoutOnMount: () => any;Log the user out and redirect them to login.
To be used as a catch-all route for anonymous users in a secure app.
See Also
CoreAdminRoutes
function mergeRefs
mergeRefs: <T = any>( refs: Array<MutableRefObject<T> | LegacyRef<T>>) => RefCallback<T>;function mergeTranslations
mergeTranslations: (...translationsModules: object[]) => any;Compose translations from multiple packages for a single language (eg: 'english').
Use it to merge translations from addons with the main react-admin translations.
Example 1
import * as React from "react"; import { Admin, Resource, mergeTranslations } from 'react-admin'; import polyglotI18nProvider from 'ra-i18n-polyglot'; import englishMessages from 'ra-language-english'; import englishTreeMessages from 'ra-tree-language-english';
const messages = { en: mergeTranslations(englishMessages, englishTreeMessages), }; const i18nProvider = polyglotI18nProvider( locale => messages[locale] ? messages[locale] : messages.en );
const App = () => ( <Admin i18nProvider={i18nProvider}> ... );
function parseQueryFromLocation
parseQueryFromLocation: ({ search }: { search: any }) => Partial<ListParams>;function queryReducer
queryReducer: Reducer<ListParams, ActionTypes>;This reducer is for the react-router query string.
function removeDoubleSlashes
removeDoubleSlashes: (path: string) => string;function removeEmpty
removeEmpty: (object: any) => {};function removeKey
removeKey: (target: any, path: any) => any;function resolveBrowserLocale
resolveBrowserLocale: ( defaultLocale?: string, options?: { fullLocale?: boolean }) => string;Resolve the browser locale according to the value of the global window.navigator
Use it to determine the locale at runtime.
Parameter defaultLocale
Defaults to 'en'
Parameter options
Parameter
{boolean} options.fullLocale Defaults to false
Example 1
import * as React from "react"; import { Admin, Resource, resolveBrowserLocale } from 'react-admin'; import polyglotI18nProvider from 'ra-i18n-polyglot'; import englishMessages from 'ra-language-english'; import frenchMessages from 'ra-language-french';
const messages = { fr: frenchMessages, en: englishMessages, }; const i18nProvider = polyglotI18nProvider( locale => messages[locale] ? messages[locale] : messages.en, resolveBrowserLocale() );
const App = () => ( <Admin i18nProvider={i18nProvider}> ... );
function sanitizeFetchType
sanitizeFetchType: (fetchType: string) => string;function sanitizeFieldRestProps
sanitizeFieldRestProps: (props: any) => any;function sanitizeInputRestProps
sanitizeInputRestProps: ({ afterSubmit, allowNull, alwaysOn, beforeSubmit, component, data, defaultValue, error, format, formatOnBlur, initializeForm, input, isEqual, isRequired, label, limitChoicesToValue, locale, meta, multiple, name, options, optionText, optionValue, parse, record, ref, refetch, render, resource, setFilter, setPagination, setSort, shouldUnregister, source, submitError, subscription, textAlign, translate, translateChoice, validate, validateFields, value, ...rest}: any) => any;function sanitizeListRestProps
sanitizeListRestProps: (props: any) => {};Select the props not injected by the useListController hook to be used inside the List children to sanitize props injected by List This is an implementation of omit()
function setSubmissionErrors
setSubmissionErrors: ( errors: FieldValues, setError: UseFormSetError<FieldValues>) => void;This internal function is used to convert an object matching the form shape with errors to a format compatible with react-hook-form. It's used to handle submission errors. Only useful when you are implementing a custom form without leveraging our Form component.
Example 1
const MyForm = () => { const { register, handleSubmit, setError } = useForm(); const onSubmit = data => { return saveAsync(data).catch(error => setSubmissionErrors(error.body.details)); };
return ( <form onSubmit={handleSubmit(onSubmit)}> ... ); };
function shallowEqual
shallowEqual: (objA: any, objB: any) => boolean;function substituteTokens
substituteTokens: (template: any, data: any) => any;Replace tokens by their value in the given string
Parameter template
The template with interpolation tokens, e.g. 'Hello, %{name}'
Parameter data
The data to interpolate, e.g. { name: 'John' }
Returns
{string} The interpolated string, e.g. 'Hello, John'
function testDataProvider
testDataProvider: (overrides?: Partial<DataProvider>) => DataProvider;function useApplyInputDefaultValues
useApplyInputDefaultValues: ({ inputProps, isArrayInput, fieldArrayInputControl,}: Props) => void;function useArrayInput
useArrayInput: (props?: UseFieldArrayReturn) => UseFieldArrayReturn;A hook to access an array input methods as provided by react-hook-form. Useful to create custom array input iterators.
See Also
{ArrayInput}
https://react-hook-form.com/docs/usefieldarray
function useAugmentedForm
useAugmentedForm: <RecordType = any>( props: UseAugmentedFormProps<RecordType>) => { form: any; handleSubmit: any; formHandleSubmit: any };Wrapper around react-hook-form's useForm
This hook adds the following features to react-hook-form's useForm:
- form initialization based on RecordContext - validation based on a validate function - sanitization of empty values - notification on invalid form - stop form submission event propagation
function useAuthenticated
useAuthenticated: <ParamsType = any>({ params, logoutOnFailure, ...options}?: UseAuthenticatedOptions<ParamsType>) => any;Restrict access to authenticated users. Redirect anonymous users to the login page.
Use it in your custom page components to require authentication.
You can set additional
authParamsat will if your authProvider requires it.Example 1
import { Admin, CustomRoutes, useAuthenticated } from 'react-admin';
const FooPage = () => { const { isPending } = useAuthenticated(); if (isPending) return null; return ; }
const customRoutes = [ <Route path="/foo" element={} /> ];
const App = () => ( {customRoutes} );
function useAuthProvider
useAuthProvider: < AuthProviderType extends AuthProvider = AuthProvider>() => AuthProviderType;Get the authProvider stored in the context
function useAuthState
useAuthState: <ErrorType = Error>( params?: any, logoutOnFailure?: boolean, queryOptions?: UseAuthStateOptions<ErrorType>) => any;Hook for getting the authentication status
Calls the authProvider.checkAuth() method asynchronously.
The return value updates according to the authProvider request state:
- isPending: true just after mount, while the authProvider is being called. false once the authProvider has answered. - authenticated: true while loading. then true or false depending on the authProvider response.
To avoid rendering a component and force waiting for the authProvider response, use the useAuthState() hook instead of the useAuthenticated() hook.
You can render different content depending on the authenticated status.
Parameter params
Any params you want to pass to the authProvider
Parameter logoutOnFailure
: Optional. Whether the user should be logged out if the authProvider fails to authenticate them. False by default.
Returns
The current auth check state. Destructure as { authenticated, error, isPending }.
Example 1
import { useAuthState, Loading } from 'react-admin';
const MyPage = () => { const { isPending, authenticated } = useAuthState(); if (isPending) { return ; } if (authenticated) { return ; } return ; };
See Also
useAuthenticated()
function useBasename
useBasename: () => any;Get the string to append to all links to the admin app.
Useful when the app is mounted on a sub path, e.g. '/admin'.
This hook is used internally by all react-admin components that contain a link, and requires that the basename is set via the
<BasenameContextProvider>component (or via the<Admin>component, which calls BasenameContextProvider internally).Example 1
import { useBasename } from 'react-admin';
const ArticleLink = ({ title, id }) => { const basename = useBasename(); return <a href={
${basename}/articles/${id}}>{title}; };See Also
BasenameContextProvider
function useBulkDeleteController
useBulkDeleteController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props: UseBulkDeleteControllerParams<RecordType, ErrorType>) => UseBulkDeleteControllerReturn;function useBulkExport
useBulkExport: <RecordType extends RaRecord<Identifier> = any>( options?: UseBulkExportOptions<RecordType>) => UseBulkExportResult;A hook that provides a callback to export the selected records from the nearest ListContext and call the exporter function for them.
function useCanAccess
useCanAccess: < RecordType extends Record<string, any> = Record<string, any>, ErrorType extends Error = Error>( params: UseCanAccessOptions<RecordType, ErrorType>) => UseCanAccessResult<ErrorType>;A hook that calls the authProvider.canAccess() method using react-query for a provided resource and action (and optionally a record).
The return value updates according to the request state:
- start: { isPending: true } - success: { canAccess: true | false, isPending: false } - error: { error: [error from provider], isPending: false }
Useful to enable or disable features based on users permissions.
Parameter params
Any params you want to pass to the authProvider
Parameter
{string} params.resource The resource to check access for
Parameter
{string} params.action The action to check access for
Parameter
{Object} params.record Optional. The record to check access for
Returns
Return the react-query result and a canAccess property which is a boolean indicating the access status
Example 1
import { useCanAccess } from 'react-admin';
const PostDetail = () => { const { isPending, canAccess, error } = useCanAccess({ resource: 'posts', action: 'read', }); if (isPending || !canAccess) { return null; } if (error) { return {error.message}; } return ; };
function useCanAccessCallback
useCanAccessCallback: < RecordType extends Record<string, any> = Record<string, any>, ErrorType = Error>( options?: Omit< UseMutationOptions< boolean, ErrorType, UseCanAccessCallbackOptions<RecordType> >, 'mutationFn' >) => any;A hook that returns a function you can call to determine whether user has access to the given resource
Example 1
import { Datagrid, List, TextField, useCanAccessCallback } from 'react-admin';
const UserList = () => { const checkAccess = useCanAccessCallback();
const handleRowClick = (id: Identifier, resource: string, record: Record) => { try { const canAccess = checkAccess({ resource: 'users', action: 'edit', record }); return canAccess ? "edit" : "show"; } catch (error) { console.error(error); } };
return ( <Datagrid onClick={handleRowClick}> ); };
function useCanAccessResources
useCanAccessResources: < RecordType extends Record<string, any> = Record<string, any>, ErrorType extends Error = Error>( params: UseCanAccessResourcesOptions<RecordType, Error>) => UseCanAccessResourcesResult<ErrorType>;Checks whether users can access the provided resources.
useCanAccessResourcesreturns an object describing the state of the request:- start: { isPending: true } - success: { canAccess: Object<string, boolean>, isPending: false } - error: { error: [error from provider], isPending: false }
Parameter params
Any params you want to pass to the authProvider
Parameter
{string} params.action The action to check access for
Parameter
{string[]} params.resources The list of resources to check access for
Parameter
{Object} params.record Optional. The record to check access for
Returns
Return the react-query result and a canAccess property which is a map of the resources and their access status { [resource: string]: boolean }
Example 1
import { useCanAccessResources } from 'react-admin';
const UserList = ({ record }) => { const { isPending, canAccess } = useCanAccessResources({ action: 'read', resources: ['users.id', 'users.name', 'users.email'], record });
if (isPending) { return null; } return ( <SimpleList primaryText={record => canAccess.users.name ? record.name : ''} secondaryText={record => canAccess.users.email ? record.email : ''} tertiaryText={record => canAccess.users.id ? record.id : ''} /> ); };
function useCheckAuth
useCheckAuth: () => CheckAuth;Get a callback for calling the authProvider.checkAuth() method. In case of rejection, redirects to the login page, displays a notification, and throws an error.
This is a low level hook. See those more specialized hooks for common authentication tasks, based on useCheckAuth.
Returns
{Function} checkAuth callback
Example 1
import { useCheckAuth } from 'react-admin';
const MyProtectedPage = () => { const checkAuth = useCheckAuth(); useEffect(() => { checkAuth().catch(() => {}); }, []); return Private content: EZAEZEZAET } // tip: use useAuthenticated() hook instead
const MyPage = () => { const checkAuth = useCheckAuth(); const [authenticated, setAuthenticated] = useState(true); // optimistic auth useEffect(() => { checkAuth({}, false) .then(() => setAuthenticated(true)) .catch(() => setAuthenticated(false)); }, []); return authenticated ? : ; } // tip: use useAuthState() hook instead
See Also
useAuthenticated
useAuthState
function useCheckForApplicationUpdate
useCheckForApplicationUpdate: ( options: UseCheckForApplicationUpdateOptions) => void;Checks if the application code has changed and calls the provided onNewVersionAvailable function when needed.
It checks for code update by downloading the provided URL (default to the HTML page) and comparing the hash of the response with the hash of the current page.
Parameter options
The options
Parameter
{Function} options.onNewVersionAvailable The function to call when a new version of the application is available.
Parameter
{string} options.url Optional. The URL to download to check for code update. Defaults to the current URL.
Parameter
{RequestInit} options.fetchOptions Optional. The options passed to fetch function when checking for update.
Parameter
{number} options.interval Optional. The interval in milliseconds between two checks. Defaults to 3600000 (1 hour).
Parameter
{boolean} options.disabled Optional. Whether the check should be disabled. Defaults to false.
function useChoicesContext
useChoicesContext: < ChoicesType extends RaRecord<Identifier> = RaRecord<Identifier>>( options?: Partial<ChoicesContextValue<any>> & { choices?: ChoicesType[] }) => ChoicesContextValue<ChoicesType>;function useCloseNotification
useCloseNotification: () => any;function useCreate
useCreate: < RecordType extends Omit<RaRecord<Identifier>, 'id'> = any, MutationError = unknown, ResultRecordType extends RaRecord<Identifier> = RecordType & { id: Identifier }>( resource?: string, params?: Partial<CreateParams<Partial<RecordType>>>, options?: UseCreateOptions<RecordType, MutationError, ResultRecordType>) => UseCreateResult<RecordType, boolean, MutationError, ResultRecordType>;Get a callback to call the dataProvider.create() method, the result and the loading state.
Parameter resource
Parameter params
The create parameters { data }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }
Params params.data The record to create, e.g. { title: 'hello, world' }
Returns
The current mutation state. Destructure as [create, { data, error, isPending }].
The return value updates according to the request state:
- initial: [create, { isPending: false, isIdle: true }] - start: [create, { isPending: true }] - success: [create, { data: [data from response], isPending: false, isSuccess: true }] - error: [create, { error: [error from response], isPending: false, isError: true }]
The create() function must be called with a resource and a parameter object: create(resource, { data, meta }, options)
This hook uses react-query useMutation under the hood. This means the state object contains mutate, isIdle, reset and other react-query methods.
Example 1
// set params when calling the create callback
import { useCreate, useRecordContext } from 'react-admin';
const LikeButton = () => { const record = useRecordContext(); const like = { postId: record.id }; const [create, { isPending, error }] = useCreate(); const handleClick = () => { create('likes', { data: like }) } if (error) { return ERROR; } return <button disabled={isPending} onClick={handleClick}>Like; };
Example 2
// set params when calling the hook
import { useCreate, useRecordContext } from 'react-admin';
const LikeButton = () => { const record = useRecordContext(); const like = { postId: record.id }; const [create, { isPending, error }] = useCreate('likes', { data: like }); if (error) { return ERROR; } return <button disabled={isPending} onClick={() => create()}>Like; };
Example 3
// TypeScript const [create, { data }] = useCreate('products', { data: product }); -- data is Product
See Also
https://tanstack.com/query/v5/docs/react/reference/useMutation
function useCreateController
useCreateController: < RecordType extends Omit<RaRecord<Identifier>, 'id'> = any, MutationOptionsError = Error, ResultRecordType extends RaRecord<Identifier> = RecordType & { id: Identifier }>( props?: CreateControllerProps<RecordType, MutationOptionsError, ResultRecordType>) => CreateControllerResult<RecordType>;Prepare data for the Create view
Parameter props
The props passed to the Create component.
{Object} controllerProps Fetched data and callbacks for the Create view
Example 1
import { useCreateController } from 'react-admin'; import CreateView from './CreateView';
const MyCreate = props => { const controllerProps = useCreateController(props); return <CreateView {...controllerProps} {...props} />; }
function useCreatePath
useCreatePath: () => any;Get a callback to create a link to a given page in the admin app.
The callback expects an object as parameter, containing the following properties: - type: 'list', 'edit', 'show' or 'create' - resource - id (optional), for 'edit' or 'show' pages
This is used internally by react-admin to allow default components to work in applications that are mounted on a sub path, e.g. '/admin'. If your app is mounted in the root path, you don't need it, and you can create links by hand, e.g. '/articles/1/show'.
Example 1
import { useCreatePath, useRecordContext } from 'react-admin'; import { useNavigate } from 'react-router-dom';
const PostEditButton = () => { const createPath = useCreatePath(); const record = useRecordContext(); const navigate = useNavigate();
const handleClick = () => { const link = createPath({ type: 'edit', resource: 'posts', id: record.id }); navigate(link); };
return <button onClick={handleClick}>Edit Post; };
function useDataProvider
useDataProvider: < TDataProvider extends DataProvider<string> = DataProvider<string>>() => TDataProvider;function useDataTableCallbacksContext
useDataTableCallbacksContext: () => any;function useDataTableColumnFilterContext
useDataTableColumnFilterContext: () => any;function useDataTableColumnRankContext
useDataTableColumnRankContext: () => any;function useDataTableConfigContext
useDataTableConfigContext: () => any;function useDataTableDataContext
useDataTableDataContext: < RecordType extends RaRecord<Identifier> = any>() => RecordType[];function useDataTableRenderContext
useDataTableRenderContext: () => any;function useDataTableSelectedIdsContext
useDataTableSelectedIdsContext: () => any;function useDataTableSortContext
useDataTableSortContext: () => any;function useDataTableStoreContext
useDataTableStoreContext: () => any;function useDebouncedEvent
useDebouncedEvent: <Args extends unknown[], Return>( callback: (...args: Args) => Return, delay: number) => any;Hook somewhat equivalent to useEvent, but with a debounce Returns a debounced callback which will not change across re-renders unless the callback or delay changes
See Also
https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
https://github.com/facebook/react/issues/14099#issuecomment-440013892
function useDeepCompareEffect
useDeepCompareEffect: (callback: any, inputs: any) => void;function useDefaultTitle
useDefaultTitle: () => any;Get the application title defined at the
<Admin>levelExample 1
import { useDefaultTitle } from 'react-admin';
const AppBar = () => { const defaultTitle = useDefaultTitle(); return {defaultTitle}; }
function useDelete
useDelete: < RecordType extends RaRecord<Identifier> = any, MutationError = unknown>( resource?: string, params?: Partial<DeleteParams<RecordType>>, options?: UseDeleteOptions<RecordType, MutationError>) => UseDeleteResult<RecordType, MutationError, boolean>;Get a callback to call the dataProvider.delete() method, the result and the loading state.
Parameter resource
Parameter params
The delete parameters { id, previousData }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } } May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' }
Params params.id The resource identifier, e.g. 123 params.previousData The record before the update is applied
Returns
The current mutation state. Destructure as [deleteOne, { data, error, isPending }].
The return value updates according to the request state:
- initial: [deleteOne, { isPending: false, isIdle: true }] - start: [deleteOne, { isPending: true }] - success: [deleteOne, { data: [data from response], isPending: false, isSuccess: true }] - error: [deleteOne, { error: [error from response], isPending: false, isError: true }]
The deleteOne() function must be called with a resource and a parameter object: deleteOne(resource, { id, previousData, meta }, options)
This hook uses react-query useMutation under the hood. This means the state object contains mutate, isIdle, reset and other react-query methods.
Example 1
// set params when calling the deleteOne callback
import { useDelete, useRecordContext } from 'react-admin';
const DeleteButton = () => { const record = useRecordContext(); const [deleteOne, { isPending, error }] = useDelete(); const handleClick = () => { deleteOne('likes', { id: record.id, previousData: record }) } if (error) { return ERROR; } return <button disabled={isPending} onClick={handleClick}>Delete; };
Example 2
// set params when calling the hook
import { useDelete, useRecordContext } from 'react-admin';
const DeleteButton = () => { const record = useRecordContext(); const [deleteOne, { isPending, error }] = useDelete('likes', { id: record.id, previousData: record }); if (error) { return ERROR; } return <button disabled={isPending} onClick={() => deleteOne()}>Delete; };
Example 3
// TypeScript const [delete, { data }] = useDelete('products', { id, previousData: product }); -- data is Product
See Also
https://tanstack.com/query/v5/docs/react/reference/useMutation
function useDeleteMany
useDeleteMany: < RecordType extends RaRecord<Identifier> = any, MutationError = unknown>( resource?: string, params?: Partial<DeleteManyParams<RecordType>>, options?: UseDeleteManyOptions<RecordType, MutationError, boolean>) => UseDeleteManyResult<RecordType, MutationError, boolean>;Get a callback to call the dataProvider.delete() method, the result and the loading state.
Parameter resource
Parameter params
The delete parameters { ids }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } } May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' }
Params params.ids The resource identifiers, e.g. [123, 456]
Returns
The current mutation state. Destructure as [deleteMany, { data, error, isPending }].
The return value updates according to the request state:
- initial: [deleteMany, { isPending: false, isIdle: true }] - start: [deleteMany, { isPending: true }] - success: [deleteMany, { data: [data from response], isPending: false, isSuccess: true }] - error: [deleteMany, { error: [error from response], isPending: false, isError: true }]
The deleteMany() function must be called with a resource and a parameter object: deleteMany(resource, { ids, meta }, options)
This hook uses react-query useMutation under the hood. This means the state object contains mutate, isIdle, reset and other react-query methods.
Example 1
// set params when calling the deleteMany callback
import { useDeleteMany } from 'react-admin';
const BulkDeletePostsButton = ({ selectedIds }) => { const [deleteMany, { isPending, error }] = useDeleteMany(); const handleClick = () => { deleteMany('posts', { ids: selectedIds }) } if (error) { return ERROR; } return <button disabled={isPending} onClick={handleClick}>Delete selected posts; };
Example 2
// set params when calling the hook
import { useDeleteMany } from 'react-admin';
const BulkDeletePostsButton = ({ selectedIds }) => { const [deleteMany, { isPending, error }] = useDeleteMany('posts', { ids: selectedIds }); const handleClick = () => { deleteMany() } if (error) { return ERROR; } return <button disabled={isPending} onClick={handleClick}>Delete selected posts; };
Example 3
// TypeScript const [deleteMany, { data }] = useDeleteMany('products', { ids }); -- data is Product
See Also
https://tanstack.com/query/v5/docs/react/reference/useMutation
function useEditController
useEditController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props?: EditControllerProps<RecordType, ErrorType>) => EditControllerResult<RecordType, ErrorType>;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.
Parameter props
The props passed to the Edit component.
{Object} controllerProps Fetched data and callbacks for the Edit view
Example 1
import { useEditController } from 'react-admin'; import EditView from './EditView';
const MyEdit = () => { const controllerProps = useEditController({ resource: 'posts', id: 123 }); return <EditView {...controllerProps} {...props} />; }
function useEvent
useEvent: <Args extends unknown[], Return>( fn: (...args: Args) => Return) => (...args: Args) => Return;Alternative to useCallback that doesn't update the callback when dependencies change
See Also
https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
https://github.com/facebook/react/issues/14099#issuecomment-440013892
function useFieldValue
useFieldValue: <RecordType extends Record<string, any> = Record<string, any>>( params: UseFieldValueOptions<RecordType>) => any;A hook that gets the value of a field of the current record.
Parameter params
The hook parameters
Parameter
params.source The field source
Parameter
params.record The record to use. Uses the record from the RecordContext if not provided
Parameter
params.defaultValue The value to return when the field value is empty
Returns
The field value
Example 1
const MyField = (props: { source: string }) => { const value = useFieldValue(props); return {value}; }
function useFilterContext
useFilterContext: () => FilterContextType;function useFormGroup
useFormGroup: (name: string) => FormGroupState;Retrieve a specific form group data such as its validation status (valid/invalid) or or whether its inputs have been updated (dirty/pristine)
Parameter name
The form group name
Returns
{FormGroupState} The form group state
Example 1
import { Edit, SimpleForm, TextInput, FormGroupContextProvider, useFormGroup, minLength } from 'react-admin'; import { Accordion, AccordionDetails, AccordionSummary, Typography } from '@mui/material'; import ExpandMoreIcon from '@mui/icons-material/ExpandMoreIcon';
const PostEdit = () => ( <AccordionSummary expandIcon={} aria-controls="options-content" id="options-header" > Options <TextInput source="teaser" validate={minLength(20)} /> );
const AccordionSectionTitle = ({ children, name }) => { const formGroupState = useFormGroup(name); return ( <Typography color={!formGroupState.isValid && formGroupState.isDirty ? 'error' : 'inherit'}> {children} ); }
function useFormGroupContext
useFormGroupContext: () => any;Retrieve the name of the form group the consumer belongs to. May be undefined if the consumer is not inside a form group.
function useFormGroups
useFormGroups: () => any;Retrieve the form groups management context. Used by inputs to register themselves into a form group.
function useFormIsDirty
useFormIsDirty: () => boolean;function useGetArrayInputNewItemDefaults
useGetArrayInputNewItemDefaults: ( fields: UseFieldArrayReturn) => (inputs?: ReactNode) => any;function useGetIdentity
useGetIdentity: <ErrorType extends Error = Error>( options?: UseGetIdentityOptions<ErrorType>) => any;Return the current user identity by calling authProvider.getIdentity() on mount
The return value updates according to the call state:
- mount: { isPending: true } - success: { identity, refetch: () => {}, isPending: false } - error: { error: Error, isPending: false }
The implementation is left to the authProvider.
Returns
The current user identity. Destructure as { isPending, identity, error, refetch }.
Example 1
import { useGetIdentity, useGetOne } from 'react-admin';
const PostDetail = ({ id }) => { const { data: post, isPending: postLoading } = useGetOne('posts', { id }); const { identity, isPending: identityLoading } = useGetIdentity(); if (postLoading || identityLoading) return <>Loading...</>; if (!post.lockedBy || post.lockedBy === identity.id) { // post isn't locked, or is locked by me return <PostEdit post={post} /> } else { // post is locked by someone else and cannot be edited return <PostShow post={post} /> } }
function useGetList
useGetList: <RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( resource: string, params?: Partial<GetListParams>, options?: UseGetListOptions<RecordType, ErrorType>) => any;Call the dataProvider.getList() method and return the resolved result as well as the loading state.
The return value updates according to the request state:
- start: { isPending: true, refetch } - success: { data: [data from store], total: [total from response], isPending: false, refetch } - error: { error: [error from response], isPending: false, refetch }
This hook will return the cached result when called a second time with the same parameters, until the response arrives.
Parameter resource
The resource name, e.g. 'posts'
Parameter params
The getList parameters { pagination, sort, filter, meta }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }
Params params.pagination The request pagination { page, perPage }, e.g. { page: 1, perPage: 10 } params.sort The request sort { field, order }, e.g. { field: 'id', order: 'DESC' } params.filter The request filters, e.g. { title: 'hello, world' } params.meta Optional meta parameters
Returns
The current request state. Destructure as { data, total, error, isPending, refetch }.
Example 1
import { useGetList } from 'react-admin';
const LatestNews = () => { const { data, total, isPending, error } = useGetList( 'posts', { pagination: { page: 1, perPage: 10 }, sort: { field: 'published_at', order: 'DESC' } } ); if (isPending) { return ; } if (error) { return ERROR; } return {data.map(item => <li key={item.id}>{item.title} )}; };
function useGetMany
useGetMany: <RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( resource: string, params: Partial<GetManyParams<RecordType>>, options?: UseGetManyOptions<RecordType, ErrorType>) => UseQueryResult<RecordType[], ErrorType>;Call the dataProvider.getMany() method and return the resolved result as well as the loading state.
The return value updates according to the request state:
- start: { isPending: true, refetch } - success: { data: [data from store], isPending: false, refetch } - error: { error: [error from response], isPending: false, refetch }
This hook will return the cached result when called a second time with the same parameters, until the response arrives.
Parameter resource
The resource name, e.g. 'posts'
Parameter params
The getMany parameters { ids, meta }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }
Params params.ids The ids to get, e.g. [123, 456, 789] params.meta Optional meta parameters
Returns
The current request state. Destructure as { data, error, isPending, refetch }.
Example 1
import { useGetMany } from 'react-admin';
const PostTags = ({ post }) => { const { data, isPending, error } = useGetMany( 'tags', { ids: post.tags }, ); if (isPending) { return ; } if (error) { return ERROR; } return {data.map(tag => <li key={tag.id}>{tag.name} )}; };
function useGetManyAggregate
useGetManyAggregate: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( resource: string, params: Partial<GetManyParams<RecordType>>, options?: UseGetManyAggregateOptions<RecordType, ErrorType>) => UseQueryResult<RecordType[], ErrorType>;Call the dataProvider.getMany() method and return the resolved result as well as the loading state.
The return value updates according to the request state:
- start: { isPending: true, isFetching: true, refetch } - success: { data: [data from response], isPending: false, isFetching: false, refetch } - error: { error: [error from response], isPending: false, isFetching: false, refetch }
This hook will return the cached result when called a second time with the same parameters, until the response arrives.
This hook aggregates and deduplicates calls to the same resource, so for instance, if an app calls:
useGetManyAggregate('tags', [1, 2, 3]); useGetManyAggregate('tags', [3, 4]);
during the same tick, the hook will only call the dataProvider once with the following parameters:
dataProvider.getMany('tags', [1, 2, 3, 4])
Parameter resource
The resource name, e.g. 'posts'
Parameter params
The getMany parameters { ids, meta }
Parameter options
Options object to pass to the dataProvider.
Parameter
{boolean} options.enabled Flag to conditionally run the query. If it's false, the query will not run
Parameter
{Function} options.onSuccess Side effect function to be executed upon success, e.g. { onSuccess: { refresh: true } }
Parameter
{Function} options.onError Side effect function to be executed upon failure, e.g. { onError: error => notify(error.message) }
Params params.ids The ids to get, e.g. [123, 456, 789] params.meta Optional meta parameters
Returns
The current request state. Destructure as { data, error, isPending, isFetching, refetch }.
Example 1
import { useGetManyAggregate, useRecordContext } from 'react-admin';
const PostTags = () => { const record = useRecordContext(); const { data, isPending, error } = useGetManyAggregate('tags', { ids: record.tagIds }); if (isPending) { return ; } if (error) { return ERROR; } return ( {data.map(tag => ( <li key={tag.id}>{tag.name} ))} ); };
function useGetManyReference
useGetManyReference: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( resource: string, params?: Partial<GetManyReferenceParams>, options?: UseGetManyReferenceHookOptions<RecordType, ErrorType>) => any;Call the dataProvider.getManyReference() method and return the resolved result as well as the loading state.
The return value updates according to the request state:
- start: { isPending: true, refetch } - success: { data: [data from store], total: [total from response], isPending: false, refetch } - error: { error: [error from response], isPending: false, refetch }
This hook will return the cached result when called a second time with the same parameters, until the response arrives.
Parameter resource
The resource name, e.g. 'posts'
Parameter params
The getManyReference parameters { target, id, pagination, sort, filter, meta }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }
Params params.target The target resource key, e.g. 'post_id' params.id The identifier of the record to look for in target, e.g. '123' params.pagination The request pagination { page, perPage }, e.g. { page: 1, perPage: 10 } params.sort The request sort { field, order }, e.g. { field: 'id', order: 'DESC' } params.filter The request filters, e.g. { title: 'hello, world' } params.meta Optional meta parameters
Returns
The current request state. Destructure as { data, total, error, isPending, refetch }.
Example 1
import { useGetManyReference, useRecordContext } from 'react-admin';
const PostComments = () => { const record = useRecordContext(); // fetch all comments related to the current record const { data, isPending, error } = useGetManyReference( 'comments', { target: 'post_id', id: record.id, pagination: { page: 1, perPage: 10 }, sort: { field: 'published_at', order: 'DESC' } } ); if (isPending) { return ; } if (error) { return ERROR; } return {data.map(comment => <li key={comment.id}>{comment.body} )}; };
function useGetOne
useGetOne: <RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( resource: string, { id, meta }: Partial<GetOneParams<RecordType>>, options?: UseGetOneOptions<RecordType, ErrorType>) => UseQueryResult<RecordType, ErrorType>;Call the dataProvider.getOne() method and return the resolved value as well as the loading state.
The return value updates according to the request state:
- start: { isPending: true, isFetching: true, refetch } - success: { data: [data from response], isPending: false, refetch } - error: { error: [error from response], isPending: false, refetch }
This hook will return the cached result when called a second time with the same parameters, until the response arrives.
Parameter resource
The resource name, e.g. 'posts'
Parameter params
The getOne parameters { id, meta }, e.g. { id: 123 }
Parameter options
Options object to pass to the react-query queryClient.
Params id a resource identifier, e.g. 123
Options enabled Flag to conditionally run the query. If it's false, the query will not run onSuccess Side effect function to be executed upon success, e.g. { onSuccess: { refresh: true } } onError Side effect function to be executed upon failure, e.g. { onError: error => notify(error.message) }
Returns
The current request state. Destructure as { data, error, isPending, refetch }.
Example 1
import { useGetOne, useRecordContext } from 'react-admin';
const UserProfile = () => { const record = useRecordContext(); const { data, isPending, error } = useGetOne('users', { id: record.id }); if (isPending) { return ; } if (error) { return ERROR; } return User {data.username}; };
function useGetPathForRecord
useGetPathForRecord: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>>( options?: UseGetPathForRecordOptions<RecordType>) => string | false | undefined;Get a path for a record, based on the current resource and the link type.
Accepted link types are 'edit', 'show', a route string, false, or a function returning one of these types.
Example 1
// basic usage (leverages RecordContext, ResourceContext and ResourceDefinitionContext) const EditLink = () => { const path = useGetPathForRecord(); return path ? <Link to={path}>Edit : null; };
// controlled mode const EditLink = ({ record, resource }) => { const path = useGetPathForRecord({ record, resource, link: 'edit' }); return path ? <Link to={path}>Edit : null; };
// the link option can be a function const EditLink = ({ record, resource }) => { const path = useGetPathForRecord({ record, resource, link: (record, resource) => record.canEdit ? 'edit' : false }); return path ? <Link to={path}>Edit : null; };
// the link option can be a function returning a promise const EditLink = ({ record, resource }) => { const path = useGetPathForRecord({ record, resource, link: async (record, resource) => { const canEdit = await canEditRecord(record, resource); return canEdit ? 'edit' : false; }}); return path ? <Link to={path}>Edit : null; };
function useGetPathForRecordCallback
useGetPathForRecordCallback: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>>( options?: UseGetPathForRecordCallbackOptions) => any;function useGetPermissions
useGetPermissions: () => GetPermissions;Get a callback for calling the authProvider.getPermissions() method.
Returns
{Function} getPermissions callback
This is a low level hook. See those more specialized hooks offering state handling.
Example 1
import { useGetPermissions } from 'react-admin';
const Roles = () => { const [permissions, setPermissions] = useState([]); const getPermissions = useGetPermissions(); useEffect(() => { getPermissions().then(permissions => setPermissions(permissions)) }, []) return ( {permissions.map((permission, key) => ( <li key={key}>{permission} ))} ); }
See Also
useAuthProvider
usePermissions
function useGetRecordId
useGetRecordId: (recordId?: Identifier) => Identifier;Helper hook to get the current
recordId.recordIdis obtained from parameters if passed as a parameter, or from theRecordContextif there is one, or, lastly, from the react-router URL.Parameter recordId
optional if used inside a RecordContextProvider or if recordId can be guessed from the URL
Returns
The
recordIddetermined in this manner.Example 1
const recordId = useGetRecordId();
function useGetRecordRepresentation
useGetRecordRepresentation: (resource?: string) => (record: any) => ReactNode;Get the default representation of a record (either a string or a React node)
Example 1
// No customization const getRecordRepresentation = useGetRecordRepresentation('posts'); getRecordRepresentation({ id: 1, title: 'Hello' }); // => "#1"
Example 2
// With const getRecordRepresentation = useGetRecordRepresentation('posts'); getRecordRepresentation({ id: 1, title: 'Hello' }); // => "Hello"
function useGetResourceLabel
useGetResourceLabel: () => GetResourceLabel;A hook which returns function to get a translated resource name. It will use the label option of the
Resourcecomponent if it was provided.Returns
{GetResourceLabel} A function which takes a resource name and an optional number indicating the number of items (used for pluralization) and returns a translated string.
Example 1
const Menu = () => { const resources = useResourceDefinitions(); const getResourceLabel = useGetResourceLabel();
return ( {Object.keys(resources).map(name => ( <li key={name}> {getResourceLabel(name, 2)} ))} ) }
function useGetValidationErrorMessage
useGetValidationErrorMessage: () => (error: ValidationErrorMessage) => string;Example 1
const MyInput = props => { const { field, fieldState } = useController(props); useEffect(() => { if (fieldState.error) { const errorMessage = useGetValidationErrorMessage(fieldState.error); alert(errorMessage); } }, [fieldState.error]);
return ( <input {...field} /> ); }
See Also
ValidationErrorMessage
ValidationErrorMessageWithArgs
Deprecated
This internal hook returns a function that can translate an error message. It handles simple string errors and those which have a message and args. Only useful if you are implementing custom inputs without leveraging our useInput hook.
function useHandleAuthCallback
useHandleAuthCallback: (options?: UseHandleAuthCallbackOptions) => any;This hook calls the
authProvider.handleCallback()method on mount. This is meant to be used in a route called by an external authentication service (e.g. Auth0) after the user has logged in. By default, it redirects to application home page upon success, or to theredirectTolocation returned byauthProvider. handleCallback.Returns
An object containing { isPending, data, error, refetch }.
function useHasDashboard
useHasDashboard: () => any;Returns true if the app has a dashboard defined at the level.
Example 1
import { useHasDashboard } from 'react-admin';
const MyMenu = () => { const hasDashboard = useHasDashboard(); return ( {hasDashboard && } ); }
function useI18nProvider
useI18nProvider: () => any;Get the i18nProvider instance declared in the component
Example 1
const CurrentLanguage = () => { const i18nProvider = useI18nProvider(); const locale = i18nProvider.getLocale(); return {locale}; };
function useInfiniteGetList
useInfiniteGetList: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( resource: string, params?: Partial<GetListParams>, options?: UseInfiniteGetListOptions<RecordType, ErrorType>) => any;Call the dataProvider.getList() method and return the resolved result as well as the loading state. The return from useInfiniteGetList is equivalent to the return from react-hook form useInfiniteQuery.
Parameter resource
The resource name, e.g. 'posts'
Parameter params
The getList parameters { pagination, sort, filter, meta }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { fetchNextPage(); } }
Params params.pagination The request pagination { page, perPage }, e.g. { page: 1, perPage: 10 } params.sort The request sort { field, order }, e.g. { field: 'id', order: 'DESC' } params.filter The request filters, e.g. { title: 'hello, world' } params.meta Optional meta parameters
Returns
The current request state. Destructure as { data, total, error, isPending, isSuccess, hasNextPage, fetchNextPage }.
Example 1
import { useInfiniteGetList } from 'react-admin';
const LatestNews = () => { const { data, total, isPending, error, hasNextPage, fetchNextPage } = useInfiniteGetList( 'posts', { pagination: { page: 1, perPage: 10 }, sort: { field: 'published_at', order: 'DESC' } } ); if (isPending) { return ; } if (error) { return ERROR; } return ( <> {data?.pages.map(page => { return page.data.map(post => ( <li key={post.id}>{post.title} )); })} <button disabled={!hasNextPage} onClick={() => fetchNextPage()}> Fetch next page </> ); };
See Also
https://tanstack.com/query/v5/docs/react/reference/useInfiniteQuery
This hook will return the cached result when called a second time with the same parameters, until the response arrives.
function useInfiniteListController
useInfiniteListController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props?: InfiniteListControllerProps<RecordType, ErrorType>) => InfiniteListControllerResult<RecordType, ErrorType>;Prepare data for the InfiniteList view
Parameter props
The props passed to the InfiniteList component.
{Object} controllerProps Fetched and computed data for the List view
Example 1
import { useInfiniteListController } from 'react-admin'; import ListView from './ListView';
const MyList = props => { const controllerProps = useInfiniteListController(props); return <ListView {...controllerProps} {...props} />; }
function useInfinitePaginationContext
useInfinitePaginationContext: () => InfinitePaginationContextValue;Hook to read the infinite pagination callbacks from the InfinitePaginationContext.
Must be used within a <InfinitePaginationContext.Provider> (e.g. as a descendent of or ).
{Object} InfinitePaginationContextValue {Function} fetchNextPage a callback to fetch the next page {Function} fetchPreviousPage a callback to fetch the previous page
Returns
{InfinitePaginationContextValue} infinite pagination callbacks
See Also
useInfiniteListController for how the callbacks are built
function useInput
useInput: <ValueType = any>(props: any) => UseInputValue;function useIsAuthPending
useIsAuthPending: (params: UseIsAuthPendingParams) => boolean;A hook that returns true if the authProvider is currently checking the authentication status or the user's access rights.
Parameter params
Parameter
params.action The action to check access for
Parameter
params.resource The resource to check access for (optional). Defaults to the resource of the current ResourceContext.
Returns
{boolean} true if the authProvider is currently checking the authentication status or the user's access rights, false otherwise.
function useIsDataLoaded
useIsDataLoaded: (queryKey: any, options?: { enabled?: boolean }) => any;Check if react-query has already fetched data for a query key.
This hook is reactive.
Returns
{boolean} true if the data is loaded, false otherwise
Example 1
const isCustomerLoaded = useIsDataLoaded(['customers', 'getOne', { id: customerId }]);
function useIsMounted
useIsMounted: () => any;function useIsOffline
useIsOffline: () => boolean;Hook to determine if the application is offline. It uses the onlineManager from react-query to check the online status. It returns true if the application is offline, false otherwise.
Returns
{boolean} - True if offline, false if online.
function useList
useList: <RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props: UseListOptions<RecordType, ErrorType>) => UseListValue<RecordType, ErrorType>;Handle filtering, sorting and pagination on local data.
Returns the data and callbacks expected by .
Parameter props
Parameter
{RaRecord[]} props.data An array of records
Parameter
{Boolean} props.isFetching: Optional. A boolean indicating whether the data is being loaded
Parameter
{Boolean} props.isLoading: Optional. A boolean indicating whether the data has been loaded at least once
Parameter
{Error | String} props.error: Optional. The error if any occurred while loading the data
Parameter
{Object} props.filter: Optional. An object containing the filters applied on the data
Parameter
{Number} props.page: Optional. The initial page index
Parameter
{Number} props.perPage: Optional. The initial page size
Parameter
{SortPayload} props.sort: Optional. The initial sort (field and order)
Parameter
{filterCallback} prop.filterCallback Optional. A function that allows you to make a custom filter
Example 1
const data = [ { id: 1, name: 'Arnold' }, { id: 2, name: 'Sylvester' }, { id: 3, name: 'Jean-Claude' }, ]
const MyComponent = () => { const listContext = useList({ data }); return ( <ListContextProvider value={listContext}> ); };
function useListContext
useListContext: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>() => ListControllerResult<RecordType, ErrorType>;Hook to read the list controller props from the ListContext.
Used within a (e.g. as a descendent of ).
Returns
{ListControllerResult} list controller props
Example 1
// custom list view
import { useListContext } from 'react-admin';
const MyList = () => { const { data, isPending } = useListContext(); if (isPending) { return <>Loading...</>; } return ( {data.map(record => ( <li key={record.id}>{record.name} ))} ); }
Example 2
// custom pagination
import { useListContext } from 'react-admin'; import { Button, Toolbar } from '@mui/material'; import ChevronLeft from '@mui/icons-material/ChevronLeft'; import ChevronRight from '@mui/icons-material/ChevronRight';
const PrevNextPagination = () => { const { page, perPage, total, setPage } = useListContext(); const nbPages = Math.ceil(total / perPage) || 1; return ( nbPages > 1 && {page > 1 && <Button color="primary" key="prev" onClick={() => setPage(page - 1)}> Prev } {page !== nbPages && <Button color="primary" key="next" onClick={() => setPage(page + 1)}> Next } ); }
See Also
useListController for how it is filled
function useListContextWithProps
useListContextWithProps: <RecordType extends RaRecord<Identifier> = any>( props?: any) => Partial<ListControllerResult<RecordType, Error>>;Hook to read the list controller props from the ListContext.
Mostly used within a <ListContext.Provider> (e.g. as a descendent of or ).
But you can also use it without a <ListContext.Provider>. In this case, it is up to you to pass all the necessary props (see the list below).
The given props will take precedence over context values.
{Object} ListControllerProps {Object} data an array of the list records, e.g. [{ id: 123, title: 'hello world' }, { ... }] {integer} total the total number of results for the current filters, excluding pagination. Useful to build the pagination controls. e.g. 23 {boolean} isFetching boolean that is true on mount, and false once the data was fetched {boolean} isLoading boolean that is false until the data is available {integer} page the current page. Starts at 1 {Function} setPage a callback to change the page, e.g. setPage(3) {integer} perPage the number of results per page. Defaults to 25 {Function} setPerPage a callback to change the number of results per page, e.g. setPerPage(25) {Object} sort a sort object { field, order }, e.g. { field: 'date', order: 'DESC' } {Function} setSort a callback to change the sort, e.g. setSort({ field : 'name', order: 'ASC' }) {Object} filterValues a dictionary of filter values, e.g. { title: 'lorem', nationality: 'fr' } {Function} setFilters a callback to update the filters, e.g. setFilters(filters, displayedFilters) {Object} displayedFilters a dictionary of the displayed filters, e.g. { title: true, nationality: true } {Function} showFilter a callback to show one of the filters, e.g. showFilter('title', defaultValue) {Function} hideFilter a callback to hide one of the filters, e.g. hideFilter('title') {Array} selectedIds an array listing the ids of the selected rows, e.g. [123, 456] {Function} onSelect callback to change the list of selected rows, e.g. onSelect([456, 789]) {Function} onSelectAll callback to select all the records, e.g. onSelectAll({ limit: 50, queryOptions: { meta: { foo: 'bar' } } }) {Function} onToggleItem callback to toggle the selection of a given record based on its id, e.g. onToggleItem(456) {Function} onUnselectItems callback to clear the selection, e.g. onUnselectItems(); {string} defaultTitle the translated title based on the resource, e.g. 'Posts' {string} resource the resource name, deduced from the location. e.g. 'posts'
Parameter props
Props passed to the useListContext hook
Returns
{ListControllerResult} list controller props
See Also
useListController for how it is filled
function useListController
useListController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props?: ListControllerProps<RecordType, ErrorType>) => ListControllerResult<RecordType, ErrorType>;Prepare data for the List view
Parameter props
The props passed to the List component.
{Object} controllerProps Fetched and computed data for the List view
Example 1
import { useListController } from 'react-admin'; import ListView from './ListView';
const MyList = props => { const controllerProps = useListController(props); return <ListView {...controllerProps} {...props} />; }
function useListFilterContext
useListFilterContext: () => ListFilterContextValue;Hook to read the list props from the ListFilterContext.
Must be used within a .
Returns
{ListFilterContextValue} list controller props
See Also
useListController for how it is filled
function useListPaginationContext
useListPaginationContext: () => ListPaginationContextValue;Hook to read the list pagination controller props from the ListPaginationContext.
Must be used within a (e.g. as a descendent of or ).
Returns
{ListPaginationContextValue} list controller props
See Also
useListController for how it is filled
function useListParams
useListParams: ({ debounce, disableSyncWithLocation, filterDefaultValues, perPage, resource, sort, storeKey,}: ListParamsOptions) => [Parameters, Modifiers];Get the list parameters (page, sort, filters) and modifiers.
These parameters are merged from 3 sources: - the query string from the URL - the params stored in the state (from previous navigation) - the options passed to the hook (including the filter defaultValues)
Returns
{Array} A tuple [parameters, modifiers]. Destructure as [ { page, perPage, sort, order, filter, filterValues, displayedFilters, requestSignature }, { setFilters, hideFilter, showFilter, setPage, setPerPage, setSort } ]
Example 1
const [listParams, listParamsActions] = useListParams({ resource: 'posts', location: location // From react-router. Injected to your component by react-admin inside a List filterDefaultValues: { published: true }, sort: { field: 'published_at', order: 'DESC' }, perPage: 25 });
const { page, perPage, sort, order, filter, filterValues, displayedFilters, requestSignature } = listParams;
const { setFilters, hideFilter, showFilter, setPage, setPerPage, setSort, } = listParamsActions;
function useListSortContext
useListSortContext: () => ListSortContextValue;Hook to read the list sort controller props from the ListSortContext.
Must be used within a (e.g. as a descendent of or ).
Returns
{ListSortContextValue} list controller props
See Also
useListController for how it is filled
function useLoading
useLoading: () => boolean;Get the state of the dataProvider connection.
Returns true if a query or a mutation is pending.
Custom implementation because react-query's useIsFetching and useIsMutating render each time the number of active queries changes, which is too often.
See Also
useIsFetching
useIsMutating
function useLocales
useLocales: (options?: UseLocalesOptions) => any;A hook that gets the available locales from the i18nProvider.
Example 1
import { useLocales } from 'react-admin';
const LocaleSelector = () => { const locales = useLocales(); const [currentLocale, setCurrentLocale] = useLocaleState();
return ( <select onChange={event => setCurrentLocale(event.target.value)}> {locales.map(locale => ( <option key={locale.locale} value={locale.locale}> {locale.name} )} ); }
function useLogin
useLogin: () => Login;Get a callback for calling the authProvider.login() method and redirect to the previous authenticated page (or the home page) on success.
Returns
{Function} login callback
Example 1
import { useLogin } from 'react-admin';
const LoginButton = () => { const [loading, setLoading] = useState(false); const login = useLogin(); const handleClick = { setLoading(true); login({ username: 'john', password: 'p@ssw0rd' }, '/posts') .then(() => setLoading(false)); } return <button onClick={handleClick}>Login; }
See Also
useAuthProvider
function useLogout
useLogout: () => Logout;Get a callback for calling the authProvider.logout() method, redirect to the login page, and clear the store.
Returns
{Function} logout callback
Example 1
import { useLogout } from 'react-admin';
const LogoutButton = () => { const logout = useLogout(); const handleClick = () => logout(); return <button onClick={handleClick}>Logout; }
See Also
useAuthProvider
function useLogoutIfAccessDenied
useLogoutIfAccessDenied: () => LogoutIfAccessDenied;Returns a callback used to call the authProvider.checkError() method and an error from the dataProvider. If the authProvider rejects the call, the hook logs the user out and shows a logged out notification.
Used in the useDataProvider hook to check for access denied responses (e.g. 401 or 403 responses) and trigger a logout.
Returns
{Function} logoutIfAccessDenied callback
Example 1
import { useLogoutIfAccessDenied, useNotify, DataProviderContext } from 'react-admin';
const FetchRestrictedResource = () => { const dataProvider = useContext(DataProviderContext); const logoutIfAccessDenied = useLogoutIfAccessDenied(); const notify = useNotify() useEffect(() => { dataProvider.getOne('secret', { id: 123 }) .catch(error => { logoutIfAccessDenied(error); notify('server error', { type: 'error' }); }) }, []); // ... }
See Also
useLogout
useDataProvider
function useMutationMiddlewares
useMutationMiddlewares: < MutateFunc extends (...args: any[]) => any = (...args: any[]) => any>() => UseMutationMiddlewaresResult<MutateFunc>;Internal hook used to handle mutation middlewares.
Example 1
// We have a form creating an order for a new customer. // The form contains the customer fields in addition to the order fields // but they should be saved as a new customer resource record // and the order should only reference this new customer type Order = { id: string; reference: string }; type OrderCreateFormData = { id: string; reference: string; customer: Customer }; type Customer = { id: string; email: string; firstName: string; lastName: string };
const CustomerForm = props => { const [createCustomer] = useCreate(); const middleware: Middleware<UseCreateResult[0]> = useCallback(async (resource, params, next) => { const { data } = params; const { user, ...orderData } = data; const { data = newCustomer } = await createCustomer('customers', { data: user }); const orderDataWithCustomer = { ...orderData, customerId: newCustomer.id }; next(resource, { data: orderDataWithCustomer }); }, [createCustomer]); useRegisterMutationMiddleware(middleware);
return ( <> </> ); }
function useMutationWithMutationMode
useMutationWithMutationMode: < ErrorType = Error, TData extends { data?: unknown } = { data?: unknown }, TVariables = unknown>( params: TVariables, options: UseMutationWithMutationModeOptions<ErrorType, TData, TVariables>) => UseMutationWithMutationModeResult<boolean, ErrorType, TData, TVariables>;function useNotificationContext
useNotificationContext: () => any;function useNotify
useNotify: () => any;Hook for Notification Side Effect
Example 1
const notify = useNotify(); // simple message (info level) notify('Level complete'); // specify level notify('A problem occurred', { type: 'error' }) // pass arguments to the translation function notify('Deleted %{count} elements', { type: 'info', messageArgs: { smart_count: 23 } }) // show the action as undoable in the notification notify('Post renamed', { type: 'info', undoable: true })
function useNotifyIsFormInvalid
useNotifyIsFormInvalid: (control?: Control, enabled?: boolean) => void;This hook display an error message on submit in Form and SaveButton.
We can't do the form validity check in the form submit handler as the form state may not have been updated yet when onSubmit validation mode is enabled or when the form hasn't been touched at all.
function usePermissions
usePermissions: <PermissionsType = any, ErrorType = Error>( params?: {}, queryParams?: UsePermissionsOptions<PermissionsType, ErrorType>) => any;Hook for getting user permissions
Calls the authProvider.getPermissions() method using react-query. If the authProvider returns a rejected promise, returns empty permissions.
The return value updates according to the request state:
- start: { isPending: true } - success: { permissions: [any], isPending: false } - error: { error: [error from provider], isPending: false }
Useful to enable features based on user permissions
Parameter params
Any params you want to pass to the authProvider
Returns
The current auth check state. Destructure as { permissions, error, isPending, refetch }.
Example 1
import { usePermissions } from 'react-admin';
const PostDetail = () => { const { isPending, permissions } = usePermissions(); if (!isPending && permissions == 'editor') { return } else { return } };
function usePickSaveContext
usePickSaveContext: < ContextType extends SaveContextValue< any, (...args: any[]) => any > = SaveContextValue<any, (...args: any[]) => any>>( context: ContextType) => SaveContextValue;This hook extracts the
save,savingand mutationMode properties from either theCreateContextorEditContext. This ensures theSaveContextdoesn't rerender when those two contexts have other properties changes.
function usePreference
usePreference: { <T>(key: string, defaultValue: T): [ T, (value: T | ((value: T) => void), defaultValue?: T) => void ]; <T = undefined>(key: string, defaultValue?: T): [ T, (value: T | ((value: T) => void), defaultValue?: T) => void ]; (): [unknown, (value: unknown, defaultValue?: unknown) => void];};Get a preference value from the store
Relies on the store, using a key namespaced with the preference key from the PreferenceKeyContext
Example 1
// when used inside a PreferenceKeyContext of value 'my-app' const [theme, setTheme] = usePreference('theme', 'light'); // this is equivalent to const [theme, setTheme] = useStore('my-app.theme', 'light');
function usePreferenceInput
usePreferenceInput: ( key: string, defaultValue?: any) => { value: any; onChange: (event: any) => void; onBlur: () => void; onKeyDown: (event: any) => void;};Get the props for a preference input that changes the value on blur
Relies on
usePreference, so it's using the PreferenceKeyContextExample 1
const FontSizePreferenceInput = () => { const field = usePreferenceInput('ui.font.size', 10); return ( Font size <input id="font-size" {...field} /> ); }
function usePreferencesEditor
usePreferencesEditor: () => PreferencesEditorContextValue;function usePrevious
usePrevious: (value: any) => any;function usePrevNextController
usePrevNextController: <RecordType extends RaRecord<Identifier> = any>( props: UsePrevNextControllerProps<RecordType>) => UsePrevNextControllerResult;A hook used to fetch the previous and next record identifiers for a given record and resource.
It fetches the list of records according to the filters and the sort order configured in the list, and merges the filters and the sorting order passed as props.
usePrevNextController can be used anywhere a record context is provided (often inside a
<Show>or<Edit>component).Example 1
Simple usage
import { usePrevNextControllerProps } from 'ra-core'; const { hasPrev, hasNext, prevPath, nextPath, index, total, error, isPending, } = usePrevNextController(props);
Example 2
Custom PrevNextButton
import { UsePrevNextControllerProps, useTranslate } from 'ra-core'; import NavigateBefore from '@mui/icons-material/NavigateBefore'; import NavigateNext from '@mui/icons-material/NavigateNext'; import ErrorIcon from '@mui/icons-material/Error'; import { Link } from 'react-router-dom'; import { CircularProgress, IconButton } from '@mui/material';
const MyPrevNextButtons = props => { const { hasPrev, hasNext, nextPath, prevPath, index, total, error, isPending, } = usePrevNextController(props);
const translate = useTranslate();
if (isPending) { return <CircularProgress size={14} />; }
if (error) { return ( <ErrorIcon color="error" fontSize="small" titleAccess="error" aria-errormessage={error.message} /> ); }
return ( <IconButton component={hasPrev ? Link : undefined} to={navigateToPrev} aria-label={translate('ra.navigation.previous')} disabled={!hasPrev} > {typeof index === 'number' && ( {index + 1} / {total} )} <IconButton component={hasNext ? Link : undefined} to={navigateToNext} aria-label={translate('ra.navigation.next')} disabled={!hasNext} > ); };
function useRecordContext
useRecordContext: < RecordType extends | RaRecord<Identifier> | Omit<RaRecord<Identifier>, 'id'> = RaRecord<Identifier>>( props?: UseRecordContextParams<RecordType>) => RecordType;Hook to read the record from a RecordContext.
Must be used within a such as provided by the (e.g. as a descendent of or ) or within a (e.g. as a descendent of or )
Returns
{RaRecord} A record object
Example 1
// basic usage
import { useRecordContext } from 'ra-core';
const TitleField = () => { const record = useRecordContext(); return {record && record.title}; };
Example 2
// allow record override via props
import { useRecordContext } from 'ra-core';
const TitleField = (props) => { const record = useRecordContext(props); return {record && record.title}; }; render(<TextField record={record} />);
function useRecordFromLocation
useRecordFromLocation: (props?: UseRecordFromLocationOptions) => any;A hook that returns the record to use to override the values in a form
Parameter options
The hook options
Parameter
options.searchSource The key in the location search to use as a source for the record. Its content should be a stringified JSON object.
Parameter
options.stateSource The key in the location state to use as a source for the record
Returns
The record to use to override the values in a form
function useRecordSelection
useRecordSelection: <RecordType extends RaRecord<Identifier> = any>( args: UseRecordSelectionArgs) => UseRecordSelectionResult<RecordType>;Get the list of selected items for a resource, and callbacks to change the selection
Parameter
args.resource The resource name, e.g. 'posts'
Parameter
args.storeKey The key to use to store selected items. Pass false to disable synchronization with the store.
Parameter
args.disableSyncWithStore Controls the selection synchronization with the store
Returns
{Object} Destructure as [selectedIds, { select, unselect, toggle, clearSelection }].
function useRedirect
useRedirect: () => any;Hook for Redirection Side Effect
Example 1
const redirect = useRedirect(); // redirect to list view redirect('list', 'posts'); // redirect to edit view redirect('edit', 'posts', 123); // redirect to edit view with state data redirect('edit', 'comments', 123, {}, { record: { post_id: record.id } }); // do not redirect redirect(false); // redirect to the result of a function redirect((resource, id, data) => ...) // redirect to an absolute URL redirect('https://marmelab.com/react-admin');
function useReference
useReference: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>, ErrorType = Error>({ reference, id, options,}: UseReferenceProps<RecordType, ErrorType>) => UseReferenceResult< RecordType, ErrorType>;Fetch reference record, and return it when available
The reference prop should be the name of one of the components added as child.
Parameter option
Parameter
{string} option.reference The linked resource name
Parameter
{string} option.id The id of the reference
Parameter
{Object} option.options Options passed to the dataProvider
Returns
{UseReferenceResult} The reference record
Example 1
const { isLoading, referenceRecord } = useReference({ id: 7, reference: 'users', });
function useReferenceArrayFieldController
useReferenceArrayFieldController: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>, ReferenceRecordType extends RaRecord<Identifier> = RaRecord<Identifier>, ErrorType = Error>( props: UseReferenceArrayFieldControllerParams< RecordType, ReferenceRecordType, ErrorType >) => ListControllerResult<ReferenceRecordType, ErrorType>;Hook that fetches records from another resource specified by an array of *ids* in current record.
Parameter props
Parameter
{Object} props.record The current resource record
Parameter
{string} props.reference The linked resource name
Parameter
{string} props.resource The current resource name
Parameter
{string} props.source The key of the linked resource identifier
Parameter props
Returns
{ListControllerResult} The reference props
Example 1
const { data, error, isFetching, isPending } = useReferenceArrayFieldController({ record: { referenceIds: ['id1', 'id2']}; reference: 'reference'; resource: 'resource'; source: 'referenceIds'; });
function useReferenceArrayInputController
useReferenceArrayInputController: < RecordType extends RaRecord<Identifier> = any>( props: UseReferenceArrayInputParams<RecordType>) => ChoicesContextValue<RecordType>;Prepare data for the ReferenceArrayInput components
Parameter props
Parameter
{Object} props.record The current resource record
Parameter
{string} props.reference The linked resource name
Parameter
{string} props.resource The current resource name
Parameter
{string} props.source The key of the linked resource identifier
Parameter props
{Object} controllerProps Fetched data and callbacks for the ReferenceArrayInput components
Example 1
const { allChoices, availableChoices, selectedChoices, error, isFetching, isLoading, isPending } = useReferenceArrayInputController({ record: { referenceIds: ['id1', 'id2']}; reference: 'reference'; resource: 'resource'; source: 'referenceIds'; });
function useReferenceFieldController
useReferenceFieldController: < ReferenceRecordType extends RaRecord<Identifier> = RaRecord<Identifier>, ErrorType = Error>( options: UseReferenceFieldControllerOptions<ReferenceRecordType, ErrorType>) => UseReferenceFieldControllerResult<ReferenceRecordType, ErrorType>;function useReferenceInputController
useReferenceInputController: <RecordType extends RaRecord<Identifier> = any>( props: UseReferenceInputControllerParams<RecordType>) => ChoicesContextValue<RecordType>;A hook for choosing a reference record. Useful for foreign keys.
This hook fetches the possible values in the reference resource (using
dataProvider.getList()), it returns the possible choices as thechoicesattribute.Example 1
const { choices, // the available reference resource } = useReferenceInputController({ input, // the input props resource: 'comments', reference: 'posts', source: 'post_id', });
The hook also allow to filter results. It returns a
setFiltersfunction. It uses the value to create a filter for the query. You can also add a permanentFilter to further filter the result:Example 2
const { choices, // the available reference resource setFilter, } = useReferenceInputController({ input, // the input props resource: 'comments', reference: 'posts', source: 'post_id', permanentFilter: { author: 'john' }, });
function useReferenceManyFieldController
useReferenceManyFieldController: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>, ReferenceRecordType extends RaRecord<Identifier> = RaRecord<Identifier>, ErrorType = Error>( props: UseReferenceManyFieldControllerParams< RecordType, ReferenceRecordType, ErrorType >) => ListControllerResult<ReferenceRecordType, ErrorType>;Fetch reference records, and return them when available
Uses dataProvider.getManyReference() internally.
Parameter props
Parameter
{string} props.reference The linked resource name. Required.
Parameter
{string} props.target The target resource key. Required.
Parameter
{Object} props.filter The filter applied on the recorded records list
Parameter
{number} props.page the page number
Parameter
{number} props.perPage the number of item per page
Parameter
{Object} props.record The current resource record
Parameter
{string} props.resource The current resource name
Parameter
{Object} props.sort the sort to apply to the referenced records
Parameter
{string} props.source The key of the linked resource identifier
Parameter
{UseQuery Options} props.queryOptions
react-queryoptions`Returns
{ListControllerResult} The reference many props
Example 1
// fetch the comments related to the current post const { isPending, data } = useReferenceManyFieldController({ reference: 'comments', target: 'post_id', record: { id: 123, title: 'hello, world' }, resource: 'posts', });
function useRefresh
useRefresh: () => any;Hook for triggering a page refresh. Returns a callback function.
The callback invalidates all queries and refetches the active ones. Any component depending on react-query data will be re-rendered.
Example 1
const refresh = useRefresh(); const handleClick = () => { refresh(); };
function useRegisterMutationMiddleware
useRegisterMutationMiddleware: < MutateFunc extends (...args: any[]) => any = (...args: any[]) => any>( callback: Middleware<MutateFunc>) => void;Internal hook that registers a middleware for the save function in the current SaveContext.
Parameter callback
The middleware function.
function useRemoveFromStore
useRemoveFromStore: (hookTimeKey?: string) => any;Get a callback to remove an item from the store
Example 1
import { useRemoveFromStore } from 'react-admin';
const ResetDatagridPrefs = () { const removeItem = useRemoveFromStore();
const handleClick = () => { removeItem('datagrid.prefs'); };
return <Button onClick={hancleClick}>Reset datagrid preferences; }
function useRemoveItemsFromStore
useRemoveItemsFromStore: (hookTimeKeyPrefix?: string | null) => any;Get a callback to remove all item with a certain key prefix from the store
Example 1
import { useRemoveItemsFromStore } from 'react-admin';
const ResetDatagridPrefs = () { const removeItems = useRemoveItemsFromStore();
const handleClick = () => { removeItems('datagrid.prefs'); };
return <Button onClick={hancleClick}>Reset datagrid preferences; }
function useResetErrorBoundaryOnLocationChange
useResetErrorBoundaryOnLocationChange: (resetErrorBoundary: () => void) => void;A hook to use inside the component passed to FallbackComponent of react-error-boundary. It resets the error boundary state whenever the location changes
Parameter resetErrorBoundary
function useResetStore
useResetStore: () => any;Get a callback to remove all items from the store
Example 1
import { useResetStore } from 'react-admin';
const ResetPrefs = () { const reset = useResetStore();
const handleClick = () => { reset(); };
return <Button onClick={handleClick}>Reset preferences; }
function useResourceContext
useResourceContext: < ResourceInformationsType extends Partial<{ resource: string }>>( props?: ResourceInformationsType) => ResourceContextValue;Hook to read the resource from the ResourceContext.
Must be used within a (e.g. as a descendent of or any reference related components), or called with a resource prop.
Returns
{ResourceContextValue} The resource name, e.g. 'posts'
Example 1
const ResourceName = (props) => { const resource = useResourceContext(props); const getResourceLabel = useGetResourceLabel(); return <>{getResourceLabel(resource, 1)}</>; }
// use it in a resource context const MyComponent = () => ( ... );
// override resource via props const MyComponent = () => ( <> ... </> );
function useResourceDefinition
useResourceDefinition: <OptionsType extends ResourceOptions = any>( props?: UseResourceDefinitionOptions) => ResourceDefinition<OptionsType>;Hook to get the definition of a given resource
Example 1
// Get the current resource definition (based on ResourceContext)
const definition = useResourceDefinition(); console.log(definition); // { // name: 'posts', // hasList: true, // hasEdit: true, // hasShow: true, // hasCreate: true, // options: {}, // icon: PostIcon, // }
Example 2
// Pass a resource prop to check a different resource definition
const definition = useResourceDefinition({ resource: 'posts' });
function useResourceDefinitionContext
useResourceDefinitionContext: () => any;function useResourceDefinitions
useResourceDefinitions: < OptionsType extends ResourceOptions = any>() => ResourceDefinitions<OptionsType>;Get the definition of the all resources
Example 1
const definitions = useResourceDefinitions(); console.log(definitions.posts); // { // name: 'posts', // hasList: true, // hasEdit: true, // hasShow: true, // hasCreate: true, // options: {}, // icon: PostIcon, // recordRepresentation: 'title', // }
function useResourceTranslation
useResourceTranslation: (params: UseResourceTranslationOptions) => any;function useRestoreScrollPosition
useRestoreScrollPosition: (storeKey: string, debounceMs?: number) => void;A hook that tracks the scroll position and restores it when the component mounts.
Parameter storeKey
The key under which to store the scroll position in the store
Parameter debounceMs
The debounce time in milliseconds
Example 1
import { useRestoreScrollPosition } from 'ra-core';
const MyCustomPage = () => { useRestoreScrollPosition('my-list');
return ( My Custom Page ); };
function useSafeSetState
useSafeSetState: <T>( initialState?: T | (() => T)) => [T | undefined, React.Dispatch<React.SetStateAction<T>>];Deprecated
use
useStateinstead, since React no longer issues warnings when calling setState on unmounted components.
function useSaveContext
useSaveContext: < PropsType extends SaveContextValue< any, (...args: any[]) => any > = SaveContextValue<any, (...args: any[]) => any>>( _props?: PropsType) => SaveContextValue;Get the save() function and its status
Used in forms.
Example 1
const { save, saving } = useSaveContext();
function useSetInspectorTitle
useSetInspectorTitle: (title: string, options?: any) => void;Set inspector title on mount
Example 1
useSetInspectorTitle('Datagrid');
function useShowController
useShowController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props?: ShowControllerProps<RecordType, ErrorType>) => ShowControllerResult<RecordType, ErrorType>;Prepare data for the Show view.
useShowController 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.
Parameter props
The props passed to the Show component.
{Object} controllerProps Fetched data and callbacks for the Show view
Example 1
import { useShowController } from 'react-admin'; import ShowView from './ShowView';
const MyShow = () => { const controllerProps = useShowController(); return <ShowView {...controllerProps} />; };
Example 2
// useShowController can also take its parameters from props
import { useShowController } from 'react-admin'; import ShowView from './ShowView';
const MyShow = () => { const controllerProps = useShowController({ resource: 'posts', id: 1234 }); return <ShowView {...controllerProps} />; };
function useSimpleFormIterator
useSimpleFormIterator: () => any;A hook that provides access to a SimpleFormIterator data (the total number of items) and mutators (add, reorder and remove). Useful to create custom array input iterators.
See Also
{SimpleFormIterator}
{ArrayInput}
function useSimpleFormIteratorItem
useSimpleFormIteratorItem: () => any;A hook that provides access to a SimpleFormIterator item meta (its index and the total number of items) and mutators (reorder and remove this remove). Useful to create custom array input iterators.
See Also
{SimpleFormIterator}
{ArrayInput}
function useSortState
useSortState: (initialSort?: SortPayload) => SortProps;Hooks to provide sort state
Parameter initialSort
Parameter
{string} initialSort.field The initial sort field
Parameter
{string} initialSort.order The initial sort order
Returns
{SortProps} The sort props
Example 1
const { sort, setSort, setSortField, setSortOrder } = useSort({ field: 'name', order: 'ASC', });
setSort({ field: 'name', order: 'ASC' }); // is the same as setSortField('name'); setSortOrder('ASC');
function useSplatPathBase
useSplatPathBase: () => any;Utility hook to get the base path of a splat path. Compatible both with react-router v6 and v7.
Example: If a splat path is defined as
/posts/:id/show/*, and the current location is/posts/12/show/3, this hook will return/posts/12/show.Solution inspired by https://github.com/remix-run/react-router/issues/11052#issuecomment-1828470203
function useStore
useStore: { <T>(key: string, defaultValue: T): [ T, (value: T | ((value: T) => void), defaultValue?: T) => void ]; <T = undefined>(key: string, defaultValue?: T): [ T, (value: T | ((value: T) => void), defaultValue?: T) => void ];};Read and write a value from the Store
useState-like hook using the global Store for persistence. Each time a store value is changed, all components using this value will be re-rendered.
Parameter key
Name of the store key. Separate with dots to namespace, e.g. 'posts.list.columns'.
Parameter defaultValue
Default value
{Object} A value and a setter for the value, in an array - just like for useState()
Example 1
import { useStore } from 'react-admin';
const PostList = () => { const [density] = useStore('posts.list.density', 'small');
return ( <Datagrid size={density}> ... ); }
// Clicking on this button will trigger a rerender of the PostList! const ChangeDensity: FC = () => { const [density, setDensity] = useStore('posts.list.density', 'small');
const changeDensity = (): void => { setDensity(density === 'small' ? 'medium' : 'small'); };
return ( <Button onClick={changeDensity}> {
Change density (current ${density})} ); };
function useStoreContext
useStoreContext: () => any;Get the Store stored in the StoreContext
function useSuggestions
useSuggestions: ({ allowCreate, choices, createText, createValue, createHintValue, limitChoicesToValue, matchSuggestion, optionText, optionValue, selectedItem, suggestionLimit, translateChoice,}: UseSuggestionsOptions) => { getChoiceText: any; getChoiceValue: any; getSuggestions: any;};function useTimeout
useTimeout: (ms?: number, key?: string) => any;A hook that returns true once a delay has expired.
Parameter ms
The delay in milliseconds
Parameter key
A key that can be used to reset the timer
Returns
true if the delay has expired, false otherwise
function useTrackScrollPosition
useTrackScrollPosition: ( storeKey: string, debounceMs?: number) => [number, (value: number | undefined) => void];A hook that tracks the scroll position and stores it.
Parameter storeKey
The key under which to store the scroll position in the store
Parameter debounceMs
The debounce time in milliseconds
Example 1
import { useTrackScrollPosition } from 'ra-core';
const MyCustomPage = () => { useTrackScrollPosition('my-list');
return ( My Custom Page ); };
function useTranslatable
useTranslatable: (options: UseTranslatableOptions) => TranslatableContextValue;Hook supplying the logic to translate a field value in multiple languages.
Parameter options
The hook options
Parameter
{string} options.defaultLocale The locale of the default selected locale. Defaults to 'en'.
Parameter
{string[]} options.locales An array of the supported locales. Each is an object with a locale and a name property. For example { locale: 'en', name: 'English' }.
Returns
An object with following properties and methods: - selectedLocale: The locale of the currently selected locale - locales: An array of the supported locales - getLabel: A function which returns the translated label for the given field - getSource: A function which returns the source for the given field - selectLocale: A function which set the selected locale
function useTranslatableContext
useTranslatableContext: () => TranslatableContextValue;Gives access to the current TranslatableContext.
Example 1
<TranslatableFields selector={} locales={['en', 'fr']} > <TextField source={getSource('title')} />
const MyLanguageSelector = () => { const { locales, selectedLocale, selectLocale, } = useTranslatableContext();
return ( <select onChange={selectLocale}> {locales.map((locale) => ( <option selected={locale.locale === selectedLocale}> {locale.name} ))} ); }
function useTranslate
useTranslate: () => TranslateFunction;Translate a string using the current locale and the translations from the i18nProvider
Example 1
import { useTranslate } from 'react-admin';
const SettingsMenu = () => { const translate = useTranslate(); return {translate('settings')}; }
See Also
Polyglot.t() https://airbnb.io/polyglot.js/#polyglotprototypetkey-interpolationoptions
{Function} A translation function, accepting two arguments - a string used as key in the translations - an interpolationOptions object
function useTranslateLabel
useTranslateLabel: () => any;function useUnique
useUnique: (options?: UseUniqueOptions) => any;A hook that returns a validation function checking for a record field uniqueness by calling the dataProvider getList function with a filter.
Example 1
// Passing options at declaration time const UserCreateForm = () => { const unique = useUnique({ message: 'Username is already used'}); return ( <TextInput source="username" validate={unique()} /> ); }
Example 2
// Passing options at call time const UserCreateForm = () => { const unique = useUnique(); return ( <TextInput source="username" validate={unique({ message: 'Username is already used'})} /> ); }
Example 3
// With additional filters const UserCreateForm = () => { const unique = useUnique(); return ( {({ formData }) => ( <TextInput source="username" validate={unique({ filter: { organization_id: formData.organization_id })} /> )} ); }
function useUnselect
useUnselect: (resource?: string, storeKey?: string) => any;Hook to Unselect the rows of a datagrid
Example 1
const unselect = useUnselect('posts'); unselect([123, 456]);
function useUnselectAll
useUnselectAll: (resource?: string, storeKey?: string) => any;Hook to unselect all row of a datagrid
Example 1
const unselectAll = useUnselectAll('posts'); unselectAll();
function useUpdate
useUpdate: <RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( resource?: string, params?: Partial<UpdateParams<RecordType>>, options?: UseUpdateOptions<RecordType, ErrorType>) => UseUpdateResult<RecordType, boolean, ErrorType>;Get a callback to call the dataProvider.update() method, the result and the loading state.
Parameter resource
Parameter params
The update parameters { id, data, previousData, meta }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } } May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' }
Params params.id The resource identifier, e.g. 123 params.data The updates to merge into the record, e.g. { views: 10 } params.previousData The record before the update is applied params.meta Optional meta data
Returns
The current mutation state. Destructure as [update, { data, error, isPending }].
The return value updates according to the request state:
- initial: [update, { isPending: false, isIdle: true }] - start: [update, { isPending: true }] - success: [update, { data: [data from response], isPending: false, isSuccess: true }] - error: [update, { error: [error from response], isPending: false, isError: true }]
The update() function must be called with a resource and a parameter object: update(resource, { id, data, previousData }, options)
This hook uses react-query useMutation under the hood. This means the state object contains mutate, isIdle, reset and other react-query methods.
Example 1
// set params when calling the update callback
import { useUpdate, useRecordContext } from 'react-admin';
const IncreaseLikeButton = () => { const record = useRecordContext(); const diff = { likes: record.likes + 1 }; const [update, { isPending, error }] = useUpdate(); const handleClick = () => { update('likes', { id: record.id, data: diff, previousData: record }) } if (error) { return ERROR; } return <button disabled={isPending} onClick={handleClick}>Like; };
Example 2
// set params when calling the hook
import { useUpdate, useRecordContext } from 'react-admin';
const IncreaseLikeButton = () => { const record = useRecordContext(); const diff = { likes: record.likes + 1 }; const [update, { isPending, error }] = useUpdate('likes', { id: record.id, data: diff, previousData: record }); if (error) { return ERROR; } return <button disabled={isPending} onClick={() => update()}>Like; };
Example 3
// TypeScript const [update, { data }] = useUpdate('products', { id, data: diff, previousData: product }); -- data is Product
See Also
https://react-query-v3.tanstack.com/reference/useMutation
function useUpdateMany
useUpdateMany: < RecordType extends RaRecord<Identifier> = any, MutationError = unknown>( resource?: string, params?: Partial<UpdateManyParams<Partial<RecordType>>>, options?: UseUpdateManyOptions<RecordType, MutationError>) => UseUpdateManyResult<RecordType, boolean, MutationError>;Get a callback to call the dataProvider.updateMany() method, the result and the loading state.
Parameter resource
Parameter params
The updateMany parameters { ids, data, meta }
Parameter options
Options object to pass to the queryClient. May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } } May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' }
Params params.ids The resource identifiers, e.g. [123, 456] params.data The updates to merge into the record, e.g. { views: 10 } params.meta Optional meta parameters
Returns
The current mutation state. Destructure as [updateMany, { data, error, isPending }].
The return value updates according to the request state:
- initial: [updateMany, { isPending: false, isIdle: true }] - start: [updateMany, { isPending: true }] - success: [updateMany, { data: [data from response], isPending: false, isSuccess: true }] - error: [updateMany, { error: [error from response], isPending: false, isError: true }]
The updateMany() function must be called with a resource and a parameter object: updateMany(resource, { ids, data, previousData }, options)
This hook uses react-query useMutation under the hood. This means the state object contains mutate, isIdle, reset and other react-query methods.
Example 1
// set params when calling the updateMany callback
import { useUpdateMany, useListContext } from 'react-admin';
const BulkResetViewsButton = () => { const { selectedIds } = useListContext(); const [updateMany, { isPending, error }] = useUpdateMany(); const handleClick = () => { updateMany('posts', { ids: selectedIds, data: { views: 0 } }); } if (error) { return ERROR; } return <button disabled={isPending} onClick={handleClick}>Reset views; };
Example 2
// set params when calling the hook
import { useUpdateMany, useListContext } from 'react-admin';
const BulkResetViewsButton = () => { const { selectedIds } = useListContext(); const [updateMany, { isPending, error }] = useUpdateMany('posts', { ids: selectedIds, data: { views: 0 } }); if (error) { return ERROR; } return <button disabled={isPending} onClick={() => updateMany()}>Reset views; };
See Also
https://tanstack.com/query/v5/docs/react/reference/useMutation
function useUserMenu
useUserMenu: () => any;A hook to retrieve the user menu context, which provides access to a function for closing the user menu.
Returns
{UserMenuContextValue}
Example 1
import { Logout, MenuItemLink, UserMenu, useUserMenu } from 'react-admin';
const ConfigurationMenu = () => { const { onClose } = useUserMenu(); return ( <MenuItemLink to="/configuration" primaryText="pos.configuration" leftIcon={} sidebarIsOpen onClick={onClose} /> ); };
export const MyUserMenu = () => ( );
function useWhyDidYouUpdate
useWhyDidYouUpdate: (name: any, props: any) => void;Debug hook showing which props updated between two renders
Example 1
const MyComponent = React.memo(props => { useWhyDidYouUpdate('MyComponent', props); return <div...; });
https://usehooks.com/useWhyDidYouUpdate/
function useWrappedSource
useWrappedSource: (source: string) => any;Get the source prop for a field or input by checking if a source context is available.
Parameter source
The original source prop
Returns
{string} The source prop, either the original one or the one modified by the SourceContext.
Example 1
const MyInput = ({ source, ...props }) => { const finalSource = useWrappedSource(source); return <input name={finalSource} {...props} />; };
function WarnWhenUnsavedChanges
WarnWhenUnsavedChanges: ({ enable, formRootPathName, formControl,}: { enable?: boolean; formRootPathName: any; formControl: any;}) => any;function withLifecycleCallbacks
withLifecycleCallbacks: ( dataProvider: DataProvider, handlers: ResourceCallbacks[]) => DataProvider;Extend a dataProvider to execute callbacks before and after read and write calls.
Parameter dataProvider
The dataProvider to wrap
Parameter handlers
An array of ResourceCallbacks
{Object} ResourceCallbacks {string} resource The resource name {AfterCreate} [afterCreate] A callback (or array of callbacks) executed after create {AfterDelete} [afterDelete] A callback (or array of callbacks) executed after delete {AfterDeleteMany} [afterDeleteMany] A callback (or array of callbacks) executed after deleteMany {AfterGetList} [afterGetList] A callback (or array of callbacks) executed after getList {AfterGetMany} [afterGetMany] A callback (or array of callbacks) executed after getMany {AfterGetManyReference} [afterGetManyReference] A callback (or array of callbacks) executed after getManyReference {AfterGetOne} [afterGetOne] A callback (or array of callbacks) executed after getOne {AfterRead} [afterRead] A callback (or array of callbacks) executed after read (getList, getMany, getManyReference, getOne) {AfterSave} [afterSave] A callback (or array of callbacks) executed after save (create, update, updateMany) {AfterUpdate} [afterUpdate] A callback (or array of callbacks) executed after update {AfterUpdateMany} [afterUpdateMany] A callback (or array of callbacks) executed after updateMany {BeforeCreate} [beforeCreate] A callback (or array of callbacks) executed before create {BeforeDelete} [beforeDelete] A callback (or array of callbacks) executed before delete {BeforeDeleteMany} [beforeDeleteMany] A callback (or array of callbacks) executed before deleteMany {BeforeGetList} [beforeGetList] A callback (or array of callbacks) executed before getList {BeforeGetMany} [beforeGetMany] A callback (or array of callbacks) executed before getMany {BeforeGetManyReference} [beforeGetManyReference] A callback (or array of callbacks) executed before getManyReference {BeforeGetOne} [beforeGetOne] A callback (or array of callbacks) executed before getOne {BeforeSave} [beforeSave] A callback (or array of callbacks) executed before save (create, update, updateMany) {BeforeUpdate} [beforeUpdate] A callback (or array of callbacks) executed before update {BeforeUpdateMany} [beforeUpdateMany] A callback (or array of callbacks) executed before updateMany
Warnings: - As queries issued in the callbacks are not done through react-query, any change in the data will not be automatically reflected in the UI. - The callbacks are not executed in a transaction. In case of error, the backend may be left in an inconsistent state. - When calling the API directly using fetch or another client, the callbacks will not be executed, leaving the backend in a possibly inconsistent state. - If a callback triggers the query it's listening to, this will lead to a infinite loop.
Example 1
const dataProvider = withLifecycleCallbacks( jsonServerProvider("http://localhost:3000"), [ { resource: "posts", afterRead: async (data, dataProvider, resource) => { // rename field to the record data.user_id = data.userId; return data; }, // executed after create, update and updateMany afterSave: async (record, dataProvider, resource) => { // update the author's nb_posts const { total } = await dataProvider.getList("users", { filter: { id: record.user_id }, pagination: { page: 1, perPage: 1 }, }); await dataProvider.update("users", { id: user.id, data: { nb_posts: total }, previousData: user, }); return record; }, beforeDelete: async (params, dataProvider, resource) => { // delete all comments linked to the post const { data: comments } = await dataProvider.getManyReference( "comments", { target: "post_id", id: params.id, } ); if (comments.length > 0) { await dataProvider.deleteMany("comments", { ids: comments.map((comment) => comment.id), }); } // update the author's nb_posts const { data: post } = await dataProvider.getOne("posts", { id: params.id, }); const { total } = await dataProvider.getList("users", { filter: { id: post.user_id }, pagination: { page: 1, perPage: 1 }, }); await dataProvider.update("users", { id: user.id, data: { nb_posts: total - 1 }, previousData: user, }); return params; }, }, ] );
Classes
class HttpError
class HttpError extends Error {}constructor
constructor(message: any, status: any, body?: any);property body
body: any;property status
status: any;class InferredElement
class InferredElement {}constructor
constructor(type?: InferredType, props?: any, children?: any);property children
children?: any;property props
props?: any;property type
type?: InferredType;method getElement
getElement: (props?: {}) => any;method getProps
getProps: () => any;method getRepresentation
getRepresentation: () => string;method isDefined
isDefined: () => boolean;Interfaces
interface BaseFieldProps
interface BaseFieldProps< RecordType extends Record<string, any> = Record<string, any>> {}property record
record?: RecordType;The current record to use. Defaults to the
RecordContextvalue.See Also
https://marmelab.com/react-admin/Fields.html#record
property resource
resource?: string;The resource name. Defaults to the
ResourceContextvalue.
property source
source: ExtractRecordPaths<RecordType>;Name of the property to display.
Example 1
const CommentList = () => ( );
See Also
https://marmelab.com/react-admin/Fields.html#source
interface ChoicesContextErrorResult
interface ChoicesContextErrorResult< RecordType extends RaRecord = any, TError = Error> extends ChoicesContextBaseValue<RecordType> {}property allChoices
allChoices: undefined;property availableChoices
availableChoices: undefined;property error
error: TError;property isPending
isPending: false;property selectedChoices
selectedChoices: undefined;property total
total: undefined;interface ChoicesContextLoadingResult
interface ChoicesContextLoadingResult<RecordType extends RaRecord = any> extends ChoicesContextBaseValue<RecordType> {}property allChoices
allChoices: undefined;property availableChoices
availableChoices: undefined;property error
error: null;property isPending
isPending: true;property selectedChoices
selectedChoices: undefined;property total
total: undefined;interface ChoicesContextRefetchErrorResult
interface ChoicesContextRefetchErrorResult< RecordType extends RaRecord = any, TError = Error> extends ChoicesContextBaseValue<RecordType> {}property allChoices
allChoices: RecordType[];property availableChoices
availableChoices: RecordType[];property error
error: TError;property isPending
isPending: false;property selectedChoices
selectedChoices: RecordType[];property total
total: number;interface ChoicesContextSuccessResult
interface ChoicesContextSuccessResult<RecordType extends RaRecord = any> extends ChoicesContextBaseValue<RecordType> {}property allChoices
allChoices: RecordType[];property availableChoices
availableChoices: RecordType[];property error
error: null;property isPending
isPending: false;property selectedChoices
selectedChoices: RecordType[];property total
total: number;interface CoreLayoutProps
interface CoreLayoutProps {}property children
children: ReactNode;interface CreateControllerProps
interface CreateControllerProps< RecordType extends Omit<RaRecord, 'id'> = any, MutationOptionsError = Error, ResultRecordType extends RaRecord = RecordType & { id: Identifier }> {}property disableAuthentication
disableAuthentication?: boolean;property hasEdit
hasEdit?: boolean;property hasShow
hasShow?: boolean;property mutationMode
mutationMode?: MutationMode;property mutationOptions
mutationOptions?: UseMutationOptions< ResultRecordType, MutationOptionsError, UseCreateMutateParams<RecordType>> & { meta?: any };property record
record?: Partial<RecordType>;property redirect
redirect?: RedirectionSideEffect;property resource
resource?: string;property transform
transform?: TransformData;interface CreateControllerResult
interface CreateControllerResult<RecordType extends Omit<RaRecord, 'id'> = any> extends SaveContextValue {}property defaultTitle
defaultTitle?: string;property isFetching
isFetching: boolean;property isLoading
isLoading: boolean;property isPending
isPending: boolean;property record
record?: Partial<RecordType>;property redirect
redirect: RedirectionSideEffect;property resource
resource: string;property saving
saving: boolean;interface CreateParams
interface CreateParams<T = any> {}interface CreatePathParams
interface CreatePathParams {}interface CreateResult
interface CreateResult<RecordType extends RaRecord = any> {}interface DeleteManyParams
interface DeleteManyParams<RecordType extends RaRecord = any> {}interface DeleteManyResult
interface DeleteManyResult<RecordType extends RaRecord = any> {}interface DeleteParams
interface DeleteParams<RecordType extends RaRecord = any> {}property id
id: RecordType['id'];property meta
meta?: any;property previousData
previousData?: RecordType;interface DeleteResult
interface DeleteResult<RecordType extends RaRecord = any> {}interface EditControllerBaseResult
interface EditControllerBaseResult<RecordType extends RaRecord = any> extends SaveContextValue<RecordType> {}property defaultTitle
defaultTitle?: string;property isFetching
isFetching: boolean;property isLoading
isLoading: boolean;property isPaused
isPaused?: boolean;property isPlaceholderData
isPlaceholderData?: boolean;property redirect
redirect: RedirectionSideEffect;property redirectOnError
redirectOnError: RedirectionSideEffect;property refetch
refetch: UseGetOneHookValue<RecordType>['refetch'];property resource
resource: string;property saving
saving: boolean;interface EditControllerLoadingErrorResult
interface EditControllerLoadingErrorResult< RecordType extends RaRecord = any, TError = Error> extends EditControllerBaseResult<RecordType> {}interface EditControllerLoadingResult
interface EditControllerLoadingResult<RecordType extends RaRecord = any> extends EditControllerBaseResult<RecordType> {}interface EditControllerProps
interface EditControllerProps< RecordType extends RaRecord = any, ErrorType = Error> {}property disableAuthentication
disableAuthentication?: boolean;property id
id?: RecordType['id'];property mutationMode
mutationMode?: MutationMode;property mutationOptions
mutationOptions?: UseUpdateOptions<RecordType, ErrorType>;property queryOptions
queryOptions?: UseGetOneOptions<RecordType, ErrorType>;property redirect
redirect?: RedirectionSideEffect;property redirectOnError
redirectOnError?: RedirectionSideEffect;property resource
resource?: string;property transform
transform?: TransformData;index signature
[key: string]: any;interface EditControllerRefetchErrorResult
interface EditControllerRefetchErrorResult< RecordType extends RaRecord = any, TError = Error> extends EditControllerBaseResult<RecordType> {}interface EditControllerSuccessResult
interface EditControllerSuccessResult<RecordType extends RaRecord = any> extends EditControllerBaseResult<RecordType> {}interface FilterPayload
interface FilterPayload {}index signature
[k: string]: any;interface GetInfiniteListResult
interface GetInfiniteListResult<RecordType extends RaRecord = any> extends GetListResult<RecordType> {}property pageParam
pageParam: number;interface GetListParams
interface GetListParams {}property filter
filter?: any;property meta
meta?: any;property pagination
pagination?: PaginationPayload;property signal
signal?: AbortSignal;property sort
sort?: SortPayload;interface GetListResult
interface GetListResult<RecordType extends RaRecord = any> {}interface GetManyParams
interface GetManyParams<RecordType extends RaRecord = any> {}interface GetManyReferenceParams
interface GetManyReferenceParams {}interface GetManyReferenceResult
interface GetManyReferenceResult<RecordType extends RaRecord = any> {}interface GetManyResult
interface GetManyResult<RecordType extends RaRecord = any> {}interface GetOneParams
interface GetOneParams<RecordType extends RaRecord = any> {}interface GetOneResult
interface GetOneResult<RecordType extends RaRecord = any> {}interface GetValidationMessageParams
interface GetValidationMessageParams {}interface InferredElementDescription
interface InferredElementDescription {}interface InferredType
interface InferredType {}property component
component?: ComponentType;property representation
representation?: (props: any, children: any) => string;property type
type?: ComponentType;interface InferredTypeMap
interface InferredTypeMap {}index signature
[key: string]: InferredType | undefined;interface InfiniteListControllerProps
interface InfiniteListControllerProps< RecordType extends RaRecord = any, ErrorType = Error> {}property debounce
debounce?: number;property disableAuthentication
disableAuthentication?: boolean;property disableSyncWithLocation
disableSyncWithLocation?: boolean;Whether to disable the synchronization of the list parameters with the current location (URL search parameters)
property exporter
exporter?: Exporter | false;property filter
filter?: FilterPayload;property filterDefaultValues
filterDefaultValues?: object;property perPage
perPage?: number;property queryOptions
queryOptions?: UseInfiniteGetListOptions<RecordType, ErrorType>;property resource
resource?: string;property sort
sort?: SortPayload;property storeKey
storeKey?: string | false;interface ListControllerBaseResult
interface ListControllerBaseResult<RecordType extends RaRecord = any> {}property defaultTitle
defaultTitle?: string;property displayedFilters
displayedFilters: any;property exporter
exporter?: Exporter | false;property filter
filter?: FilterPayload;property filterValues
filterValues: any;property hasNextPage
hasNextPage?: boolean;property hasPreviousPage
hasPreviousPage?: boolean;property hideFilter
hideFilter: (filterName: string) => void;property isFetching
isFetching?: boolean;property isLoading
isLoading?: boolean;property isPaused
isPaused?: boolean;property isPlaceholderData
isPlaceholderData?: boolean;property onSelect
onSelect: (ids: RecordType['id'][]) => void;property onSelectAll
onSelectAll: (options?: { limit?: number; queryOptions?: | UseGetListOptions<RecordType> | UseReferenceArrayFieldControllerParams<RecordType>['queryOptions'] | UseReferenceManyFieldControllerParams<RecordType>['queryOptions'];}) => void;property onToggleItem
onToggleItem: (id: RecordType['id']) => void;property onUnselectItems
onUnselectItems: (fromAllStoreKeys?: boolean) => void;property page
page: number;property perPage
perPage: number;property refetch
refetch: (() => void) | UseGetListHookValue<RecordType>['refetch'];property resource
resource: string;property selectedIds
selectedIds: RecordType['id'][];property setFilters
setFilters: (filters: any, displayedFilters?: any, debounce?: boolean) => void;property setPage
setPage: (page: number) => void;property setPerPage
setPerPage: (page: number) => void;property setSort
setSort: (sort: SortPayload) => void;property showFilter
showFilter: (filterName: string, defaultValue: any) => void;property sort
sort: SortPayload;interface ListControllerErrorResult
interface ListControllerErrorResult< RecordType extends RaRecord = any, TError = Error> extends ListControllerBaseResult<RecordType> {}interface ListControllerLoadingResult
interface ListControllerLoadingResult<RecordType extends RaRecord = any> extends ListControllerBaseResult<RecordType> {}interface ListControllerProps
interface ListControllerProps< RecordType extends RaRecord = any, ErrorType = Error> {}property debounce
debounce?: number;The debounce delay for filter queries in milliseconds. Defaults to 500ms.
Example 1
// wait 1 seconds instead of 500 milliseconds befoce calling the dataProvider const PostList = () => ( <List debounce={1000}> ... );
See Also
https://marmelab.com/react-admin/List.html#debounce
property disableAuthentication
disableAuthentication?: boolean;Allow anonymous access to the list view. Defaults to false.
Example 1
import { List } from 'react-admin';
const BoolkList = () => ( <List disableAuthentication> ... );
See Also
https://marmelab.com/react-admin/List.html#disableauthentication
property disableSyncWithLocation
disableSyncWithLocation?: boolean;Whether to disable the synchronization of the list parameters with the current location (URL search parameters)
Example 1
const Dashboard = () => ( // ... <List disableSyncWithLocation> <SimpleList primaryText={record => record.title} secondaryText={record =>
${record.views} views} tertiaryText={record => new Date(record.published_at).toLocaleDateString()} /> <List disableSyncWithLocation> <SimpleList primaryText={record => record.title} secondaryText={record =>${record.views} views} tertiaryText={record => new Date(record.published_at).toLocaleDateString()} /> )See Also
https://marmelab.com/react-admin/List.html#disablesyncwithlocation
property exporter
exporter?: Exporter<RecordType> | false;The function called when a user exports the list
Example 1
import { List, downloadCSV } from 'react-admin'; import jsonExport from 'jsonexport/dist';
const exporter = posts => { const postsForExport = posts.map(post => { const { backLinks, author, ...postForExport } = post; // omit backLinks and author postForExport.author_name = post.author.name; // add a field return postForExport; }); jsonExport(postsForExport, { headers: ['id', 'title', 'author_name', 'body'] // order fields in the export }, (err, csv) => { downloadCSV(csv, 'posts'); // download as 'posts.csv` file }); };
const PostList = () => ( <List exporter={exporter}> ... )
See Also
https://marmelab.com/react-admin/List.html#exporter
property filter
filter?: FilterPayload;Permanent filter applied to all getList queries, regardless of the user selected filters.
Example 1
export const PostList = () => ( <List filter={{ is_published: true }}> ... );
See Also
https://marmelab.com/react-admin/List.html#filter
property filterDefaultValues
filterDefaultValues?: object;The filter to apply when calling getList if the filter is empty.
Example 1
const postFilters = [ <TextInput label="Search" source="q" alwaysOn />, <BooleanInput source="is_published" alwaysOn />, , ];
export const PostList = () => ( <List filters={postFilters} filterDefaultValues={{ is_published: true }}> ... );
See Also
https://marmelab.com/react-admin/List.html#filterdefaultvalues
property perPage
perPage?: number;The number of results per page. Defaults to 10.
Example 1
export const PostList = () => ( <List perPage={25}> ... );
See Also
https://marmelab.com/react-admin/List.html#perpage
property queryOptions
queryOptions?: UseGetListOptions<RecordType, ErrorType>;The options passed to react-query's useQuery when calling getList.
Example 1
import { useNotify, useRedirect, List } from 'react-admin';
const PostList = () => { const notify = useNotify(); const redirect = useRedirect();
const onError = (error) => { notify(
Could not load list: ${error.message}, { type: 'error' }); redirect('/dashboard'); };return ( <List queryOptions={{ onError }}> ... ); }
See Also
https://marmelab.com/react-admin/List.html#queryoptions
property resource
resource?: string;The resource name. Defaults to the resource from ResourceContext.
Example 1
import { List } from 'react-admin';
const PostList = () => ( ... );
See Also
https://marmelab.com/react-admin/List.html#resource
property sort
sort?: SortPayload;The default sort field and order. Defaults to { field: 'id', order: 'ASC' }.
Example 1
export const PostList = () => ( <List sort={{ field: 'published_at', order: 'DESC' }}> ... );
See Also
https://marmelab.com/react-admin/List.html#sort
property storeKey
storeKey?: string | false;The key to use to store the current filter & sort. Pass false to disable.
Example 1
const NewerBooks = () => ( <List resource="books" storeKey="newerBooks" sort={{ field: 'year', order: 'DESC' }} > ... );
See Also
https://marmelab.com/react-admin/List.html#storekey
interface ListControllerRefetchErrorResult
interface ListControllerRefetchErrorResult< RecordType extends RaRecord = any, TError = Error> extends ListControllerBaseResult<RecordType> {}interface ListControllerSuccessResult
interface ListControllerSuccessResult<RecordType extends RaRecord = any> extends ListControllerBaseResult<RecordType> {}interface ListParams
interface ListParams {}interface ListParamsOptions
interface ListParamsOptions {}property debounce
debounce?: number;property disableSyncWithLocation
disableSyncWithLocation?: boolean;property filterDefaultValues
filterDefaultValues?: FilterPayload;property perPage
perPage?: number;property resource
resource: string;property sort
sort?: SortPayload;property storeKey
storeKey?: string | false;interface NotificationOptions
interface NotificationOptions {}property autoHideDuration
autoHideDuration?: number | null;property messageArgs
messageArgs?: any;property multiLine
multiLine?: boolean;property undoable
undoable?: boolean;index signature
[key: string]: any;interface NotificationPayload
interface NotificationPayload {}property message
readonly message: string | ReactNode;property notificationOptions
readonly notificationOptions?: NotificationOptions;property type
readonly type: NotificationType;interface Options
interface Options extends RequestInit {}property user
user?: { authenticated?: boolean; token?: string;};interface PaginationHookResult
interface PaginationHookResult {}PaginationProps {Object} {number} page: The page number. {number} perPage: The number of item per page. {Function} setPage: Set the page number {Function} setPerPage: Set the per page number {Function} setPagination: Set page and perPage pagination numbers
property page
page: number;property pagination
pagination: PaginationPayload;property perPage
perPage: number;property setPage
setPage: (page: number) => void;property setPagination
setPagination: (pagination: PaginationPayload) => void;property setPerPage
setPerPage: (perPage: number) => void;interface PaginationPayload
interface PaginationPayload {}interface QueryFunctionContext
interface QueryFunctionContext {}property signal
signal?: AbortSignal;interface RaRecord
interface RaRecord<IdentifierType extends Identifier = Identifier> extends Record<string, any> {}property id
id: IdentifierType;interface ResourceComponentInjectedProps
interface ResourceComponentInjectedProps {}interface ResourceDefinition
interface ResourceDefinition<OptionsType extends ResourceOptions = any> {}property hasCreate
readonly hasCreate?: boolean;property hasEdit
readonly hasEdit?: boolean;property hasList
readonly hasList?: boolean;property hasShow
readonly hasShow?: boolean;property icon
readonly icon?: any;property name
readonly name: string;property options
readonly options?: OptionsType;property recordRepresentation
readonly recordRepresentation?: React.ReactNode | RecordToStringFunction;interface ResourceOptions
interface ResourceOptions {}property label
label?: string;index signature
[key: string]: any;interface ResourceProps
interface ResourceProps {}property children
children?: ReactNode;property create
create?: ComponentType<any> | ReactElement;property edit
edit?: ComponentType<any> | ReactElement;property hasCreate
hasCreate?: boolean;property hasEdit
hasEdit?: boolean;property hasShow
hasShow?: boolean;property icon
icon?: ComponentType<any>;property intent
intent?: 'route' | 'registration';property list
list?: ComponentType<any> | ReactElement;property name
name: string;property options
options?: ResourceOptions;property recordRepresentation
recordRepresentation?: React.ReactNode | RecordToStringFunction;property show
show?: ComponentType<any> | ReactElement;interface SaveContextValue
interface SaveContextValue< RecordType extends RaRecord = any, MutateFunc extends (...args: any[]) => any = (...args: any[]) => any> {}property mutationMode
mutationMode?: MutationMode;property registerMutationMiddleware
registerMutationMiddleware?: (callback: Middleware<MutateFunc>) => void;property save
save?: SaveHandler<RecordType>;property saving
saving?: boolean;@deprecated. Rely on the form isSubmitting value instead
property unregisterMutationMiddleware
unregisterMutationMiddleware?: (callback: Middleware<MutateFunc>) => void;interface ShowControllerBaseResult
interface ShowControllerBaseResult<RecordType extends RaRecord = any> {}property defaultTitle
defaultTitle?: string;property isFetching
isFetching: boolean;property isLoading
isLoading: boolean;property isPaused
isPaused?: boolean;property isPlaceholderData
isPlaceholderData?: boolean;property record
record?: RecordType;property redirectOnError
redirectOnError?: RedirectionSideEffect;property refetch
refetch: UseGetOneHookValue<RecordType>['refetch'];property resource
resource: string;interface ShowControllerLoadingErrorResult
interface ShowControllerLoadingErrorResult< RecordType extends RaRecord = any, TError = Error> extends ShowControllerBaseResult<RecordType> {}interface ShowControllerLoadingResult
interface ShowControllerLoadingResult<RecordType extends RaRecord = any> extends ShowControllerBaseResult<RecordType> {}interface ShowControllerProps
interface ShowControllerProps< RecordType extends RaRecord = any, ErrorType = Error> {}property disableAuthentication
disableAuthentication?: boolean;property id
id?: RecordType['id'];property queryOptions
queryOptions?: UseGetOneOptions<RecordType, ErrorType>;property redirectOnError
redirectOnError?: RedirectionSideEffect;property resource
resource?: string;interface ShowControllerRefetchErrorResult
interface ShowControllerRefetchErrorResult< RecordType extends RaRecord = any, TError = Error> extends ShowControllerBaseResult<RecordType> {}interface ShowControllerSuccessResult
interface ShowControllerSuccessResult<RecordType extends RaRecord = any> extends ShowControllerBaseResult<RecordType> {}interface SortPayload
interface SortPayload {}interface SortProps
interface SortProps {}property setSort
setSort: (sort: SortPayload) => void;property setSortField
setSortField: (field: SortPayload['field']) => void;property setSortOrder
setSortOrder: (order: SortPayload['order']) => void;property sort
sort: SortPayload;interface Store
interface Store {}property getItem
getItem: <T = any>(key: string, defaultValue?: T) => T | undefined;property removeItem
removeItem: (key: string) => void;property removeItems
removeItems: (keyPrefix: string) => void;property reset
reset: () => void;property setItem
setItem: <T = any>(key: string, value: T) => void;property setup
setup: () => void;property subscribe
subscribe: (key: string, callback: (value: any) => void) => () => void;property teardown
teardown: () => void;interface StringMap
interface StringMap {}index signature
[key: string]: StringMap | string | undefined;interface TranslatableContextValue
interface TranslatableContextValue {}property getRecordForLocale
getRecordForLocale: GetRecordForLocale;property locales
locales: string[];property selectedLocale
selectedLocale: string;property selectLocale
selectLocale: SelectTranslatableLocale;interface TranslationMessages
interface TranslationMessages extends StringMap {}property ra
ra: { action: { // for custom translation strings [key: string]: StringMap | string; add_filter: string; add: string; back: string; bulk_actions: string; cancel: string; clear_array_input: string; clear_input_value: string; clone: string; confirm: string; create: string; create_item: string; delete: string; edit: string; export: string; list: string; refresh: string; remove_filter: string; remove_all_filters: string; remove: string; reset: string; save: string; search: string; search_columns: string; select_all: string; select_all_button: string; select_row: string; show: string; sort: string; undo: string; unselect: string; expand: string; close: string; open_menu: string; close_menu: string; update: string; move_up: string; move_down: string; open: string; toggle_theme: string; select_columns: string; update_application: string; }; boolean: { [key: string]: StringMap | string; true: string; false: string; null: string; }; page: { [key: string]: StringMap | string; create: string; dashboard: string; edit: string; error: string; list: string; loading: string; not_found: string; show: string; empty: string; invite: string; access_denied: string; authentication_error: string; }; input: { [key: string]: StringMap | string; file: { [key: string]: StringMap | string; upload_several: string; upload_single: string; }; image: { [key: string]: StringMap | string; upload_several: string; upload_single: string; }; references: { [key: string]: StringMap | string; all_missing: string; many_missing: string; single_missing: string; }; password: { [key: string]: StringMap | string; toggle_visible: string; toggle_hidden: string; }; }; message: { [key: string]: StringMap | string; about: string; access_denied: string; are_you_sure: string; authentication_error: string; auth_error: string; bulk_delete_content: string; bulk_delete_title: string; bulk_update_content: string; bulk_update_title: string; clear_array_input: string; delete_content: string; delete_title: string; details: string; error: string; invalid_form: string; loading: string; no: string; not_found: string; select_all_limit_reached: string; unsaved_changes: string; yes: string; placeholder_data_warning: string; }; navigation: { [key: string]: StringMap | string; no_results: string; no_filtered_results: string; clear_filters: string; no_more_results: string; page_out_of_boundaries: string; page_out_from_end: string; page_out_from_begin: string; page_range_info: string; partial_page_range_info: string; page_rows_per_page: string; current_page: string; page: string; first: string; last: string; next: string; previous: string; skip_nav: string; }; sort: { sort_by: string; ASC: string; DESC: string; }; auth: { [key: string]: StringMap | string; auth_check_error: string; user_menu: string; username: string; password: string; email: string; sign_in: string; sign_in_error: string; logout: string; }; notification: { [key: string]: StringMap | string; updated: string; created: string; deleted: string; bad_item: string; item_doesnt_exist: string; http_error: string; data_provider_error: string; i18n_error: string; canceled: string; logged_out: string; not_authorized: string; application_update_available: string; offline: string; }; validation: { [key: string]: StringMap | string; required: string; minLength: string; maxLength: string; minValue: string; maxValue: string; number: string; email: string; oneOf: string; regex: string; }; saved_queries: { label: string; query_name: string; new_label: string; new_dialog_title: string; remove_label: string; remove_label_with_name: string; remove_dialog_title: string; remove_message: string; help: string; }; configurable?: { customize: string; configureMode: string; inspector: { title: string; content: string; reset: string; hideAll: string; showAll: string; }; Datagrid: { title: string; unlabeled: string; }; SimpleForm: { title: string; unlabeled: string; }; SimpleList: { title: string; primaryText: string; secondaryText: string; tertiaryText: string; }; };};interface UpdateManyParams
interface UpdateManyParams<T = any> {}interface UpdateManyResult
interface UpdateManyResult<RecordType extends RaRecord = any> {}interface UpdateParams
interface UpdateParams<RecordType extends RaRecord = any> {}property data
data: Partial<RecordType>;property id
id: RecordType['id'];property meta
meta?: any;property previousData
previousData: RecordType;interface UpdateResult
interface UpdateResult<RecordType extends RaRecord = any> {}interface UseBulkDeleteControllerParams
interface UseBulkDeleteControllerParams< RecordType extends RaRecord = any, MutationOptionsError = unknown> {}property mutationMode
mutationMode?: MutationMode;property mutationOptions
mutationOptions?: UseDeleteManyOptions<RecordType, MutationOptionsError>;property resource
resource?: string;property successMessage
successMessage?: string;interface UseBulkDeleteControllerReturn
interface UseBulkDeleteControllerReturn {}property handleDelete
handleDelete: () => void;property isLoading
isLoading: boolean;property isPending
isPending: boolean;interface UseBulkExportOptions
interface UseBulkExportOptions<RecordType extends RaRecord = any> {}interface UseCanAccessLoadingErrorResult
interface UseCanAccessLoadingErrorResult<ErrorType = Error> extends QueryObserverLoadingErrorResult<boolean, ErrorType> {}property canAccess
canAccess: undefined;interface UseCanAccessLoadingResult
interface UseCanAccessLoadingResult<ErrorType = Error> extends QueryObserverLoadingResult<boolean, ErrorType> {}property canAccess
canAccess: undefined;interface UseCanAccessOptions
interface UseCanAccessOptions< RecordType extends Record<string, any> = Record<string, any>, ErrorType extends Error = Error> extends Omit<UseQueryOptions<boolean, ErrorType>, 'queryKey' | 'queryFn'> {}interface UseCanAccessRefetchErrorResult
interface UseCanAccessRefetchErrorResult<ErrorType = Error> extends QueryObserverRefetchErrorResult<boolean, ErrorType> {}property canAccess
canAccess: boolean;interface UseCanAccessResourcesLoadingErrorResult
interface UseCanAccessResourcesLoadingErrorResult<ErrorType = Error> {}interface UseCanAccessResourcesLoadingResult
interface UseCanAccessResourcesLoadingResult {}interface UseCanAccessResourcesOptions
interface UseCanAccessResourcesOptions< RecordType extends Record<string, any> = Record<string, any>, ErrorType extends Error = Error> extends Omit< UseQueryOptions<Record<string, boolean>, ErrorType>, 'queryKey' | 'queryFn' > {}interface UseCanAccessResourcesRefetchErrorResult
interface UseCanAccessResourcesRefetchErrorResult<ErrorType = Error> {}interface UseCanAccessResourcesSuccessResult
interface UseCanAccessResourcesSuccessResult {}interface UseCanAccessSuccessResult
interface UseCanAccessSuccessResult<ErrorType = Error> extends QueryObserverSuccessResult<boolean, ErrorType> {}property canAccess
canAccess: boolean;interface UseCheckForApplicationUpdateOptions
interface UseCheckForApplicationUpdateOptions {}property disabled
disabled?: boolean;property fetchOptions
fetchOptions?: RequestInit;property interval
interval?: number;property onNewVersionAvailable
onNewVersionAvailable: () => void;property url
url?: string;interface UseCreateMutateParams
interface UseCreateMutateParams<RecordType extends Omit<RaRecord, 'id'> = any> {}interface UseDataProviderOptions
interface UseDataProviderOptions {}interface UseDeleteManyMutateParams
interface UseDeleteManyMutateParams<RecordType extends RaRecord = any> {}interface UseDeleteMutateParams
interface UseDeleteMutateParams<RecordType extends RaRecord = any> {}property data
data?: Partial<RecordType>;property id
id?: RecordType['id'];property meta
meta?: any;property previousData
previousData?: any;property resource
resource?: string;interface UseFieldValueOptions
interface UseFieldValueOptions< RecordType extends Record<string, any> = Record<string, any>> {}property defaultValue
defaultValue?: any;property record
record?: RecordType;property source
source: ExtractRecordPaths<RecordType>;interface UseFormOwnProps
interface UseFormOwnProps<RecordType = any> {}property defaultValues
defaultValues?: any;property disableInvalidFormNotification
disableInvalidFormNotification?: boolean;property formRootPathname
formRootPathname?: string;property onSubmit
onSubmit?: SubmitHandler<FieldValues> | SaveHandler<RecordType>;property record
record?: Partial<RaRecord>;property sanitizeEmptyValues
sanitizeEmptyValues?: boolean;interface UseGetIdentityOptions
interface UseGetIdentityOptions<ErrorType extends Error = Error> extends Omit<UseQueryOptions<UserIdentity, ErrorType>, 'queryKey' | 'queryFn'> {}interface UseGetPathForRecordCallbackOptions
interface UseGetPathForRecordCallbackOptions {}property resource
resource?: string;interface UseGetPathForRecordOptions
interface UseGetPathForRecordOptions<RecordType extends RaRecord = RaRecord> {}interface UseListOptions
interface UseListOptions<RecordType extends RaRecord = any, ErrorType = Error> {}property data
data?: RecordType[];property error
error?: ErrorType | null;property filter
filter?: FilterPayload;property filterCallback
filterCallback?: (record: RecordType) => boolean;property isFetching
isFetching?: boolean;property isLoading
isLoading?: boolean;property isPaused
isPaused?: boolean;property isPending
isPending?: boolean;property isPlaceholderData
isPlaceholderData?: boolean;property page
page?: number;property perPage
perPage?: number;property resource
resource?: string;property sort
sort?: SortPayload;interface UseLocalesOptions
interface UseLocalesOptions {}property locales
locales?: { locale: string; name: string }[];interface UseMutationMiddlewaresResult
interface UseMutationMiddlewaresResult< MutateFunc extends (...args: any[]) => any = (...args: any[]) => any> {}property getMutateWithMiddlewares
getMutateWithMiddlewares: ( mutate: MutateFunc) => (...args: Parameters<MutateFunc>) => ReturnType<MutateFunc>;property registerMutationMiddleware
registerMutationMiddleware: (callback: Middleware<MutateFunc>) => void;property unregisterMutationMiddleware
unregisterMutationMiddleware: (callback: Middleware<MutateFunc>) => void;interface UsePrevNextControllerProps
interface UsePrevNextControllerProps<RecordType extends RaRecord = any> {}property filter
filter?: FilterPayload;property filterDefaultValues
filterDefaultValues?: FilterPayload;property limit
limit?: number;property linkType
linkType?: 'edit' | 'show';property queryOptions
queryOptions?: Omit< UseQueryOptions<{ data: RecordType[]; total?: number; pageInfo?: { hasNextPage?: boolean; hasPreviousPage?: boolean; }; }>, 'queryFn' | 'queryKey'> & { meta?: any };property resource
resource?: string;property sort
sort?: SortPayload;property storeKey
storeKey?: string | false;interface UseRecordContextParams
interface UseRecordContextParams< RecordType extends RaRecord | Omit<RaRecord, 'id'> = RaRecord> {}property record
record?: RecordType;index signature
[key: string]: any;interface UseReferenceArrayFieldControllerParams
interface UseReferenceArrayFieldControllerParams< RecordType extends RaRecord = RaRecord, ReferenceRecordType extends RaRecord = RaRecord, ErrorType = Error> {}property filter
filter?: any;property page
page?: number;property perPage
perPage?: number;property queryOptions
queryOptions?: Omit< UseQueryOptions<ReferenceRecordType[], ErrorType>, 'queryFn' | 'queryKey'>;property record
record?: RecordType;property reference
reference: string;property resource
resource?: string;property sort
sort?: SortPayload;property source
source: string;interface UseReferenceArrayInputParams
interface UseReferenceArrayInputParams<RecordType extends RaRecord = any> {}property debounce
debounce?: number;property enableGetChoices
enableGetChoices?: (filters: any) => boolean;property filter
filter?: FilterPayload;property page
page?: number;property perPage
perPage?: number;property queryOptions
queryOptions?: Omit< UseQueryOptions<{ data: RecordType[]; total?: number; pageInfo?: { hasNextPage?: boolean; hasPreviousPage?: boolean; }; }>, 'queryFn' | 'queryKey'> & { meta?: any };property record
record?: RecordType;property reference
reference: string;property resource
resource?: string;property sort
sort?: SortPayload;property source
source: string;interface UseReferenceFieldControllerOptions
interface UseReferenceFieldControllerOptions< ReferenceRecordType extends RaRecord = RaRecord, ErrorType = Error> {}property link
link?: LinkToType<ReferenceRecordType>;property queryOptions
queryOptions?: Omit< UseQueryOptions<ReferenceRecordType[], ErrorType>, 'queryFn' | 'queryKey'>;property reference
reference: string;property source
source: string;interface UseReferenceFieldControllerResult
interface UseReferenceFieldControllerResult< ReferenceRecordType extends RaRecord = RaRecord, ErrorType = Error> extends UseReferenceResult<ReferenceRecordType, ErrorType> {}property link
link?: string | false;interface UseReferenceInputControllerParams
interface UseReferenceInputControllerParams<RecordType extends RaRecord = any> {}property debounce
debounce?: number;property enableGetChoices
enableGetChoices?: (filters: any) => boolean;property filter
filter?: FilterPayload;property page
page?: number;property perPage
perPage?: number;property queryOptions
queryOptions?: Omit< UseQueryOptions< | GetListResult<RecordType> // useReference calls getManyAggregate, which returns a an array of records | RecordType[] >, 'queryFn' | 'queryKey'> & { meta?: any };property record
record?: RaRecord;property reference
reference: string;property resource
resource?: string;property sort
sort?: SortPayload;property source
source: string;interface UseReferenceManyFieldControllerParams
interface UseReferenceManyFieldControllerParams< RecordType extends Record<string, any> = Record<string, any>, ReferenceRecordType extends Record<string, any> = Record<string, any>, ErrorType = Error> {}property debounce
debounce?: number;property filter
filter?: FilterPayload;property page
page?: number;property perPage
perPage?: number;property queryOptions
queryOptions?: Omit< UseQueryOptions<{ data: ReferenceRecordType[]; total: number }, ErrorType>, 'queryKey' | 'queryFn'>;property record
record?: RecordType;property reference
reference: string;property resource
resource?: string;property sort
sort?: SortPayload;property source
source?: string;property storeKey
storeKey?: string;property target
target: string;interface UseReferenceResult
interface UseReferenceResult<RecordType extends RaRecord = any, ErrorType = Error> {}property error
error?: ErrorType | null;property isFetching
isFetching: boolean;property isLoading
isLoading: boolean;property isPaused
isPaused?: boolean;property isPending
isPending: boolean;property isPlaceholderData
isPlaceholderData?: boolean;property referenceRecord
referenceRecord?: RecordType;property refetch
refetch: UseGetManyHookValue<RecordType, ErrorType>['refetch'];interface UseResourceDefinitionOptions
interface UseResourceDefinitionOptions {}property hasCreate
readonly hasCreate?: boolean;property hasEdit
readonly hasEdit?: boolean;property hasList
readonly hasList?: boolean;property hasShow
readonly hasShow?: boolean;property recordRepresentation
readonly recordRepresentation?: React.ReactNode | RecordToStringFunction;property resource
readonly resource?: string;interface UseResourceTranslationOptions
interface UseResourceTranslationOptions {}property baseI18nKey
baseI18nKey: string;property options
options?: Record<string, any>;property resourceI18nKey
resourceI18nKey?: string;property userText
userText?: ReactNode;interface UserIdentity
interface UserIdentity {}property avatar
avatar?: string;property fullName
fullName?: string;property id
id: Identifier;index signature
[key: string]: any;interface UseSuggestionsOptions
interface UseSuggestionsOptions extends UseChoicesOptions {}property allowCreate
allowCreate?: boolean;property allowDuplicates
allowDuplicates?: boolean;property choices
choices?: any[];property createText
createText?: string;property limitChoicesToValue
limitChoicesToValue?: boolean;property matchSuggestion
matchSuggestion?: (filter: string, suggestion: any, exact?: boolean) => boolean;property selectedItem
selectedItem?: any | any[];property suggestionLimit
suggestionLimit?: number;interface UseUpdateManyMutateParams
interface UseUpdateManyMutateParams<RecordType extends RaRecord = any> {}property data
data?: Partial<RecordType>;property ids
ids?: Array<RecordType['id']>;property meta
meta?: any;property previousData
previousData?: any;property resource
resource?: string;interface UseUpdateMutateParams
interface UseUpdateMutateParams<RecordType extends RaRecord = any> {}property data
data?: Partial<RecordType>;property id
id?: RecordType['id'];property meta
meta?: any;property previousData
previousData?: any;property resource
resource?: string;interface ValidationErrorMessageWithArgs
interface ValidationErrorMessageWithArgs {}Type Aliases
type AdminChildren
type AdminChildren = | RenderResourcesFunction | Iterable<ReactNode | RenderResourcesFunction> | ReactNode;type AnyString
type AnyString = string & {};type ArrayInputContextValue
type ArrayInputContextValue = UseFieldArrayReturn;type AuthActionType
type AuthActionType = | typeof AUTH_LOGIN | typeof AUTH_LOGOUT | typeof AUTH_ERROR | typeof AUTH_CHECK | typeof AUTH_GET_PERMISSIONS;type AuthProvider
type AuthProvider = { login: (params: any) => Promise<{ redirectTo?: string | boolean } | void | any>; logout: (params: any) => Promise<void | false | string>; checkAuth: (params: any & QueryFunctionContext) => Promise<void>; checkError: (error: any) => Promise<void>; getIdentity?: (params?: QueryFunctionContext) => Promise<UserIdentity>; getPermissions?: (params: any & QueryFunctionContext) => Promise<any>; handleCallback?: ( params?: QueryFunctionContext ) => Promise<AuthRedirectResult | void | any>; canAccess?: <RecordType extends Record<string, any> = Record<string, any>>( params: QueryFunctionContext & { action: string; resource: string; record?: RecordType; } ) => Promise<boolean>; [key: string]: any; supportAbortSignal?: boolean;};authProvider types
type AuthRedirectResult
type AuthRedirectResult = { redirectTo?: string | false; logoutOnFailure?: boolean;};type CatchAllComponent
type CatchAllComponent = ComponentType<{ title?: TitleComponent }>;type CheckAuth
type CheckAuth = ( params?: any, logoutOnFailure?: boolean, redirectTo?: string) => Promise<any>;Check if the current user is authenticated by calling authProvider.checkAuth(). Logs the user out on failure.
Parameter params
The parameters to pass to the authProvider
Parameter logoutOnFailure
Whether the user should be logged out if the authProvider fails to authenticate them. True by default.
Parameter redirectTo
The login form url. Defaults to '/login'
{Promise} Resolved to the authProvider response if the user passes the check, or rejected with an error otherwise
type ChoicesContextBaseValue
type ChoicesContextBaseValue<RecordType extends RaRecord = any> = { displayedFilters: any; filter?: FilterPayload; filterValues: any; hasNextPage?: boolean; hasPreviousPage?: boolean; hideFilter: (filterName: string) => void; isFetching: boolean; isLoading: boolean; isPaused?: boolean; isPlaceholderData?: boolean; page: number; perPage: number; refetch: (() => void) | UseGetListHookValue<RecordType>['refetch']; resource: string; setFilters: (filters: any, displayedFilters?: any, debounce?: boolean) => void; setPage: (page: number) => void; setPerPage: (page: number) => void; setSort: (sort: SortPayload) => void; showFilter: (filterName: string, defaultValue: any) => void; sort: SortPayload; source: string; isFromReference: boolean;};type ChoicesContextValue
type ChoicesContextValue<RecordType extends RaRecord = any> = | ChoicesContextLoadingResult<RecordType> | ChoicesContextErrorResult<RecordType> | ChoicesContextRefetchErrorResult<RecordType> | ChoicesContextSuccessResult<RecordType>;type CloseNotificationContextValue
type CloseNotificationContextValue = () => void;type CreateMutationFunction
type CreateMutationFunction< RecordType extends Omit<RaRecord, 'id'> = any, TReturnPromise extends boolean = boolean, MutationError = unknown, ResultRecordType extends RaRecord = RecordType & { id: Identifier }> = ( resource?: string, params?: Partial<CreateParams<Partial<RecordType>>>, options?: MutateOptions< ResultRecordType, MutationError, Partial<UseCreateMutateParams<RecordType>>, unknown > & { mutationMode?: MutationMode; returnPromise?: TReturnPromise }) => Promise<TReturnPromise extends true ? ResultRecordType : void>;type CreatePathType
type CreatePathType = HintedString<'list' | 'edit' | 'show' | 'create'>;type DashboardComponent
type DashboardComponent = ComponentType<WithPermissionsChildrenParams>;type DataProvider
type DataProvider<ResourceType extends string = string> = { getList: <RecordType extends RaRecord = any>( resource: ResourceType, params: GetListParams & QueryFunctionContext ) => Promise<GetListResult<RecordType>>;
getOne: <RecordType extends RaRecord = any>( resource: ResourceType, params: GetOneParams<RecordType> & QueryFunctionContext ) => Promise<GetOneResult<RecordType>>;
getMany: <RecordType extends RaRecord = any>( resource: ResourceType, params: GetManyParams<RecordType> & QueryFunctionContext ) => Promise<GetManyResult<RecordType>>;
getManyReference: <RecordType extends RaRecord = any>( resource: ResourceType, params: GetManyReferenceParams & QueryFunctionContext ) => Promise<GetManyReferenceResult<RecordType>>;
update: <RecordType extends RaRecord = any>( resource: ResourceType, params: UpdateParams ) => Promise<UpdateResult<RecordType>>;
updateMany: <RecordType extends RaRecord = any>( resource: ResourceType, params: UpdateManyParams ) => Promise<UpdateManyResult<RecordType>>;
create: < RecordType extends Omit<RaRecord, 'id'> = any, ResultRecordType extends RaRecord = RecordType & { id: Identifier } >( resource: ResourceType, params: CreateParams ) => Promise<CreateResult<ResultRecordType>>;
delete: <RecordType extends RaRecord = any>( resource: ResourceType, params: DeleteParams<RecordType> ) => Promise<DeleteResult<RecordType>>;
deleteMany: <RecordType extends RaRecord = any>( resource: ResourceType, params: DeleteManyParams<RecordType> ) => Promise<DeleteManyResult<RecordType>>;
[key: string]: any; supportAbortSignal?: boolean;};dataProvider types
type DataProviderMatcher
type DataProviderMatcher = (resource: string) => DataProvider;type DataProviderResult
type DataProviderResult<RecordType extends RaRecord = any> = | CreateResult<RecordType> | DeleteResult<RecordType> | DeleteManyResult | GetListResult<RecordType> | GetManyResult<RecordType> | GetManyReferenceResult<RecordType> | GetOneResult<RecordType> | UpdateResult<RecordType> | UpdateManyResult;type DataTableDataContextProps
type DataTableDataContextProps<RecordType extends RaRecord = any> = | RecordType[] | undefined;type Dispatch
type Dispatch<T> = T extends (...args: infer A) => any ? (...args: A) => void : never;Misc types
type EditControllerResult
type EditControllerResult<RecordType extends RaRecord = any, ErrorType = Error> = | EditControllerLoadingResult<RecordType> | EditControllerLoadingErrorResult<RecordType, ErrorType> | EditControllerRefetchErrorResult<RecordType, ErrorType> | EditControllerSuccessResult<RecordType>;type Exporter
type Exporter<RecordType extends RaRecord = any> = ( data: RecordType[], fetchRelatedRecords: FetchRelatedRecords, dataProvider: DataProvider, resource?: string) => void | Promise<void>;type ExtractRecordPaths
type ExtractRecordPaths<T extends RecordValues> = // Trick that allows to check whether T was provided [T] extends [never] ? string : RecordPath<T>;type FetchRelatedRecords
type FetchRelatedRecords = <RecordType = any>( data: any[], field: string, resource: string) => Promise<{ [key: Identifier]: RecordType }>;type FormFunctions
type FormFunctions = { setOnSave?: SetOnSave;};type FormGroupContextValue
type FormGroupContextValue = string;type GetRecordForLocale
type GetRecordForLocale = (record: any, locale: string) => any;Returns a record where translatable fields have their values set to the value of the given locale. This is necessary because the fields rely on the RecordContext to get their values and have no knowledge of the locale.
Given the record { title: { en: 'title_en', fr: 'title_fr' } } and the locale 'fr', the record for the locale 'fr' will be { title: 'title_fr' }
type GetResourceLabel
type GetResourceLabel = (resource: string, count?: number) => string;type GetValidationMessage
type GetValidationMessage = ( params: GetValidationMessageParams) => ValidationErrorMessage;type HintedString
type HintedString<KnownValues extends string> = AnyString | KnownValues;type I18nContextProps
type I18nContextProps = I18nProvider;type I18nProvider
type I18nProvider = { translate: TranslateFunction; changeLocale: (locale: string, options?: any) => Promise<void>; getLocale: () => string; getLocales?: () => Locale[]; [key: string]: any;};type Identifier
type Identifier = string | number;data types
type InfiniteListControllerResult
type InfiniteListControllerResult< RecordType extends RaRecord = any, ErrorType = Error> = ListControllerResult<RecordType> & { fetchNextPage: InfiniteQueryObserverBaseResult< InfiniteData<GetInfiniteListResult<RecordType>>, ErrorType >['fetchNextPage']; fetchPreviousPage: InfiniteQueryObserverBaseResult< InfiniteData<GetInfiniteListResult<RecordType>>, ErrorType >['fetchPreviousPage']; isFetchingNextPage: InfiniteQueryObserverBaseResult< InfiniteData<GetInfiniteListResult<RecordType>>, ErrorType >['isFetchingNextPage']; isFetchingPreviousPage: InfiniteQueryObserverBaseResult< InfiniteData<GetInfiniteListResult<RecordType>>, ErrorType >['isFetchingPreviousPage'];};type InfinitePaginationContextValue
type InfinitePaginationContextValue = Pick< InfiniteListControllerResult, | 'fetchNextPage' | 'fetchPreviousPage' | 'isFetchingNextPage' | 'hasNextPage' | 'hasPreviousPage' | 'isFetchingPreviousPage'>;type InputProps
type InputProps<ValueType = any> = Omit< UseControllerProps, 'name' | 'defaultValue' | 'rules'> & Partial<UseControllerReturn> & { alwaysOn?: any; defaultValue?: any; format?: (value: ValueType) => any; id?: string; isRequired?: boolean; label?: ReactNode; helperText?: ReactNode; name?: string; onBlur?: (...event: any[]) => void; onChange?: (...event: any[]) => void; parse?: (value: any) => ValueType; type?: string; resource?: string; source: string; validate?: Validator | Validator[]; readOnly?: boolean; disabled?: boolean; };type LayoutComponent
type LayoutComponent = ComponentType<CoreLayoutProps>;type LegacyAuthProvider
type LegacyAuthProvider = (type: AuthActionType, params?: any) => Promise<any>;type LegacyDataProvider
type LegacyDataProvider = ( type: string, resource: string, params: any) => Promise<any>;type LinkToFunctionType
type LinkToFunctionType<RecordType extends RaRecord = RaRecord> = ( record: RecordType, reference: string) => string | false | Promise<string | false>;type LinkToType
type LinkToType<RecordType extends RaRecord = RaRecord> = | string | false | LinkToFunctionType<RecordType>;type ListControllerResult
type ListControllerResult<RecordType extends RaRecord = any, ErrorType = Error> = | ListControllerLoadingResult<RecordType> | ListControllerErrorResult<RecordType, ErrorType> | ListControllerRefetchErrorResult<RecordType, ErrorType> | ListControllerSuccessResult<RecordType>;type LoadingComponent
type LoadingComponent = ComponentType<{ loadingPrimary?: string; loadingSecondary?: string;}>;type Locale
type Locale = { locale: string; name: string;};type LoginComponent
type LoginComponent = ComponentType<{}> | ReactElement<any>;type Middleware
type Middleware<MutateFunc = (...args: any[]) => any> = MutateFunc extends ( ...a: any[]) => infer R ? (...a: [...U: Parameters<MutateFunc>, next: MutateFunc]) => R : never;type MutationFunctionWithOptions
type MutationFunctionWithOptions< TReturnPromise extends boolean = boolean, ErrorType = Error, TData extends { data?: unknown } = { data?: unknown }, TVariables = unknown> = ( params?: Partial<TVariables>, options?: MutateOptions< TData['data'], ErrorType, Partial<TVariables>, unknown > & { mutationMode?: MutationMode; returnPromise?: TReturnPromise; }) => Promise<TReturnPromise extends true ? TData['data'] : void>;type MutationMode
type MutationMode = 'pessimistic' | 'optimistic' | 'undoable';type NotificationContextType
type NotificationContextType = { notifications: NotificationPayload[]; addNotification: (notification: NotificationPayload) => void; takeNotification: () => NotificationPayload | void; resetNotifications: () => void; setNotifications: Dispatch<SetStateAction<NotificationPayload[]>>;};type NotificationType
type NotificationType = 'success' | 'info' | 'warning' | 'error';type OnError
type OnError = ( error?: any, variables?: any, onMutateResult?: any, context?: any) => void;type OnSuccess
type OnSuccess = ( response?: any, variables?: any, onMutateResult?: any, context?: any) => void;type PossibleInferredElementTypes
type PossibleInferredElementTypes = (typeof InferenceTypes)[number];type RecordPath
type RecordPath<TRecordValues extends RecordValues> = FieldPath<TRecordValues>;type RecordToStringFunction
type RecordToStringFunction = (record: any) => string;type RecordValues
type RecordValues = Record<string, any>;type RedirectionSideEffect
type RedirectionSideEffect = CreatePathType | false | RedirectToFunction;type RenderContextType
type RenderContextType = 'data' | 'header' | 'footer' | 'columnsSelector';type RenderResourcesFunction
type RenderResourcesFunction = (permissions: any) => | ReactNode // (permissions) => <><Resource /><Resource /><Resource /></> | Promise<ReactNode> // (permissions) => fetch().then(() => <><Resource /><Resource /><Resource /></>) | ResourceElement[] // // (permissions) => [<Resource />, <Resource />, <Resource />] | Promise<ResourceElement[]>;type ResourceCallback
type ResourceCallback<U> = { (params: U, dataProvider: DataProvider, resource: string): Promise<U>;};type ResourceCallbacks
type ResourceCallbacks<T extends RaRecord = any> = { resource: string; afterCreate?: ResourceCallbacksValue<CreateResult<T>>; afterDelete?: ResourceCallbacksValue<DeleteResult<T>>; afterDeleteMany?: ResourceCallbacksValue<DeleteManyResult<T>>; afterGetList?: ResourceCallbacksValue<GetListResult<T>>; afterGetMany?: ResourceCallbacksValue<GetManyResult<T>>; afterGetManyReference?: ResourceCallbacksValue<GetManyReferenceResult<T>>; afterGetOne?: ResourceCallbacksValue<GetOneResult<T>>; afterUpdate?: ResourceCallbacksValue<UpdateResult<T>>; afterUpdateMany?: ResourceCallbacksValue<UpdateManyResult<T>>; beforeCreate?: ResourceCallbacksValue<CreateParams<T>>; beforeDelete?: ResourceCallbacksValue<DeleteParams<T>>; beforeDeleteMany?: ResourceCallbacksValue<DeleteManyParams<T>>; beforeGetList?: ResourceCallbacksValue<GetListParams>; beforeGetMany?: ResourceCallbacksValue<GetManyParams>; beforeGetManyReference?: ResourceCallbacksValue<GetManyReferenceParams>; beforeGetOne?: ResourceCallbacksValue<GetOneParams<T>>; beforeUpdate?: ResourceCallbacksValue<UpdateParams<T>>; beforeUpdateMany?: ResourceCallbacksValue<UpdateManyParams<T>>;
// The following hooks don't match a dataProvider method
/** * Modify the data before it is sent to the dataProvider. * * Used in create, update, and updateMany * * Note: This callback doesn't modify the record itself, but the data argument * (which may be a diff, especially when called with updateMany). */ beforeSave?: ResourceCallbacksValue<T>; /** * Update a record after it has been read from the dataProvider * * Used in getOne, getList, getMany, and getManyReference */ afterRead?: ResourceCallbacksValue<T>; /** * Use the record after it is returned by the dataProvider. * * Used in create, update, and updateMany */ afterSave?: ResourceCallbacksValue<T>;};type ResourceCallbacksValue
type ResourceCallbacksValue<V> = ResourceCallback<V> | ResourceCallback<V>[];type ResourceContextValue
type ResourceContextValue = string | undefined;type ResourceElement
type ResourceElement = ReactElement<ResourceProps>;type RowClickFunctionBase
type RowClickFunctionBase<RecordType extends RaRecord = RaRecord> = ( id: Identifier, resource: string, record: RecordType) => string | false | Promise<string | false>;type SaveHandler
type SaveHandler<RecordType> = ( record: Partial<RecordType>, callbacks?: SaveHandlerCallbacks) => Promise<void | RecordType> | Record<string, string>;type SaveHandlerCallbacks
type SaveHandlerCallbacks = { onSuccess?: OnSuccess; onError?: OnError; transform?: TransformData; meta?: any;};type SelectTranslatableLocale
type SelectTranslatableLocale = (locale: string) => void;type SetOnSave
type SetOnSave = (onSave?: (values: object, redirect: any) => void) => void;type ShowControllerResult
type ShowControllerResult<RecordType extends RaRecord = any, ErrorType = Error> = | ShowControllerLoadingResult<RecordType> | ShowControllerLoadingErrorResult<RecordType, ErrorType> | ShowControllerRefetchErrorResult<RecordType, ErrorType> | ShowControllerSuccessResult<RecordType>;type SimpleFormIteratorContextValue
type SimpleFormIteratorContextValue = { add: (item?: any) => void; clear: () => void; remove: (index: number) => void; reOrder: (index: number, newIndex: number) => void; source: string; total: number;};type SimpleFormIteratorItemContextValue
type SimpleFormIteratorItemContextValue = { index: number; total: number; remove: () => void; reOrder: (newIndex: number) => void;};type Snapshot
type Snapshot = [key: QueryKey, value: any][];type TitleComponent
type TitleComponent = string | ReactElement<any>;type TransformData
type TransformData = ( data: any, options?: { previousData: any }) => any | Promise<any>;type TranslateFunction
type TranslateFunction = (key: string, options?: any) => string;type UndoableMutation
type UndoableMutation = (params: { isUndo: boolean }) => void;type UpdateMutationFunction
type UpdateMutationFunction< RecordType extends RaRecord = any, TReturnPromise extends boolean = boolean, ErrorType = Error> = ( resource?: string, params?: Partial<UpdateParams<RecordType>>, options?: MutateOptions< RecordType, ErrorType, Partial<UseUpdateMutateParams<RecordType>>, unknown > & { mutationMode?: MutationMode; returnPromise?: TReturnPromise }) => Promise<TReturnPromise extends true ? RecordType : void>;type UseAugmentedFormProps
type UseAugmentedFormProps<RecordType = any> = UseFormOwnProps<RecordType> & Omit<UseFormProps, 'onSubmit'> & { validate?: ValidateForm; };type UseAuthenticatedOptions
type UseAuthenticatedOptions<ParamsType> = Omit< UseQueryOptions<boolean, any> & { params?: ParamsType; }, 'queryKey' | 'queryFn'> & { logoutOnFailure?: boolean;};type UseBulkExportResult
type UseBulkExportResult = () => void;type UseCanAccessCallback
type UseCanAccessCallback< RecordType extends Record<string, any> = Record<string, any>, ErrorType = Error> = UseMutateAsyncFunction< UseCanAccessCallbackResult, ErrorType, UseCanAccessCallbackOptions<RecordType>, unknown>;type UseCanAccessCallbackOptions
type UseCanAccessCallbackOptions< RecordType extends Record<string, any> = Record<string, any>> = { resource: string; action: HintedString<'list' | 'create' | 'edit' | 'show' | 'delete'>; record?: RecordType;};type UseCanAccessCallbackResult
type UseCanAccessCallbackResult = boolean;type UseCanAccessResourcesResult
type UseCanAccessResourcesResult<ErrorType = Error> = | UseCanAccessResourcesLoadingResult | UseCanAccessResourcesLoadingErrorResult<ErrorType> | UseCanAccessResourcesRefetchErrorResult<ErrorType> | UseCanAccessResourcesSuccessResult;type UseCanAccessResult
type UseCanAccessResult<ErrorType = Error> = | UseCanAccessLoadingResult<ErrorType> | UseCanAccessLoadingErrorResult<ErrorType> | UseCanAccessRefetchErrorResult<ErrorType> | UseCanAccessSuccessResult<ErrorType>;type UseCreateOptions
type UseCreateOptions< RecordType extends Omit<RaRecord, 'id'> = any, MutationError = unknown, ResultRecordType extends RaRecord = RecordType & { id: Identifier }> = Omit< UseMutationOptions< ResultRecordType, MutationError, Partial<UseCreateMutateParams<RecordType>> >, 'mutationFn'> & { mutationMode?: MutationMode; returnPromise?: boolean; getMutateWithMiddlewares?: < CreateFunctionType extends DataProvider['create'] = DataProvider['create'] >( mutate: CreateFunctionType ) => ( ...Params: Parameters<CreateFunctionType> ) => ReturnType<CreateFunctionType>;};type UseCreateResult
type UseCreateResult< RecordType extends Omit<RaRecord, 'id'> = any, TReturnPromise extends boolean = boolean, MutationError = unknown, ResultRecordType extends RaRecord = RecordType & { id: Identifier }> = [ CreateMutationFunction< RecordType, TReturnPromise, MutationError, ResultRecordType >, UseMutationResult< ResultRecordType, MutationError, Partial<UseCreateMutateParams<RecordType>>, unknown > & { isLoading: boolean }];type UseDeleteManyOptions
type UseDeleteManyOptions< RecordType extends RaRecord = any, MutationError = unknown, TReturnPromise extends boolean = boolean> = Omit< UseMutationOptions< Array<RecordType['id']> | undefined, MutationError, Partial<UseDeleteManyMutateParams<RecordType>> >, 'mutationFn'> & { mutationMode?: MutationMode; returnPromise?: TReturnPromise };type UseDeleteManyResult
type UseDeleteManyResult< RecordType extends RaRecord = any, MutationError = unknown, TReturnPromise extends boolean = boolean> = [ ( resource?: string, params?: Partial<DeleteManyParams<RecordType>>, options?: MutateOptions< Array<RecordType['id']> | undefined, MutationError, Partial<UseDeleteManyMutateParams<RecordType>>, unknown > & { mutationMode?: MutationMode; returnPromise?: TReturnPromise } ) => Promise< TReturnPromise extends true ? Array<RecordType['id']> | undefined : void >, UseMutationResult< Array<RecordType['id']> | undefined, MutationError, Partial<DeleteManyParams<RecordType> & { resource?: string }>, unknown > & { isLoading: boolean }];type UseDeleteOptions
type UseDeleteOptions< RecordType extends RaRecord = any, MutationError = unknown> = Omit< UseMutationOptions< RecordType, MutationError, Partial<UseDeleteMutateParams<RecordType>> >, 'mutationFn'> & { mutationMode?: MutationMode; returnPromise?: boolean;};type UseDeleteResult
type UseDeleteResult< RecordType extends RaRecord = any, MutationError = unknown, TReturnPromise extends boolean = boolean> = [ ( resource?: string, params?: Partial<DeleteParams<RecordType>>, options?: MutateOptions< RecordType | undefined, MutationError, Partial<UseDeleteMutateParams<RecordType>>, unknown > & { mutationMode?: MutationMode; returnPromise?: TReturnPromise; } ) => Promise<TReturnPromise extends true ? RecordType | undefined : void>, UseMutationResult< RecordType | undefined, MutationError, Partial<DeleteParams<RecordType> & { resource?: string }>, unknown > & { isLoading: boolean }];type UseGetIdentityResult
type UseGetIdentityResult<ErrorType = Error> = QueryObserverResult< UserIdentity, ErrorType> & { identity: UserIdentity | undefined;};type UseGetListHookValue
type UseGetListHookValue<RecordType extends RaRecord = any> = UseQueryResult< RecordType[], Error> & { total?: number; pageInfo?: { hasNextPage?: boolean; hasPreviousPage?: boolean; }; meta?: any;};type UseGetListOptions
type UseGetListOptions<RecordType extends RaRecord = any, ErrorType = Error> = Omit< UseQueryOptions<GetListResult<RecordType>, ErrorType>, 'queryKey' | 'queryFn'> & { onSuccess?: (value: GetListResult<RecordType>) => void; onError?: (error: ErrorType) => void; onSettled?: (data?: GetListResult<RecordType>, error?: ErrorType | null) => void;};type UseGetManyAggregateOptions
type UseGetManyAggregateOptions< RecordType extends RaRecord = any, ErrorType = Error> = Omit<UseQueryOptions<RecordType[], ErrorType>, 'queryKey' | 'queryFn'> & { onSuccess?: (data: RecordType[]) => void; onError?: (error: ErrorType) => void; onSettled?: (data?: RecordType[], error?: ErrorType | null) => void;};type UseGetManyHookValue
type UseGetManyHookValue< RecordType extends RaRecord = any, ErrorType = Error> = UseQueryResult<RecordType[], ErrorType>;type UseGetManyOptions
type UseGetManyOptions<RecordType extends RaRecord = any, ErrorType = Error> = Omit< UseQueryOptions<RecordType[], ErrorType>, 'queryKey' | 'queryFn'> & { onSuccess?: (data: RecordType[]) => void; onError?: (error: ErrorType) => void; onSettled?: (data?: RecordType[], error?: ErrorType | null) => void;};type UseGetManyReferenceHookOptions
type UseGetManyReferenceHookOptions< RecordType extends RaRecord = any, ErrorType = Error> = Omit< UseQueryOptions<GetManyReferenceResult<RecordType>, ErrorType>, 'queryKey' | 'queryFn'> & { onSuccess?: (data: GetManyReferenceResult<RecordType>) => void; onError?: (error: ErrorType) => void; onSettled?: ( data?: GetManyReferenceResult<RecordType>, error?: ErrorType | null ) => void;};type UseGetManyReferenceHookValue
type UseGetManyReferenceHookValue< RecordType extends RaRecord = any, ErrorType = Error> = UseQueryResult<RecordType[], ErrorType> & { total?: number; pageInfo?: { hasNextPage?: boolean; hasPreviousPage?: boolean; }; meta?: any;};type UseGetOneHookValue
type UseGetOneHookValue< RecordType extends RaRecord = any, ErrorType = Error> = UseQueryResult<GetOneResult<RecordType>['data'], ErrorType>;type UseGetOneOptions
type UseGetOneOptions<RecordType extends RaRecord = any, ErrorType = Error> = Omit< UseQueryOptions<GetOneResult<RecordType>['data'], ErrorType>, 'queryKey' | 'queryFn'> & { onSuccess?: (data: GetOneResult<RecordType>['data']) => void; onError?: (error: ErrorType) => void; onSettled?: ( data?: GetOneResult<RecordType>['data'], error?: ErrorType | null ) => void;};type UseGetRouteForRecordOptions
type UseGetRouteForRecordOptions<RecordType extends RaRecord = RaRecord> = UseGetPathForRecordOptions<RecordType>;type UseHandleAuthCallbackOptions
type UseHandleAuthCallbackOptions = Omit< UseQueryOptions<AuthRedirectResult | void>, 'queryKey' | 'queryFn'> & { onSuccess?: (data: AuthRedirectResult | void) => void; onError?: (err: Error) => void; onSettled?: (data?: AuthRedirectResult | void, error?: Error | null) => void;};type UseInfiniteGetListHookValue
type UseInfiniteGetListHookValue< RecordType extends RaRecord = any, ErrorType = Error> = UseInfiniteQueryResult< InfiniteData<GetInfiniteListResult<RecordType>>, ErrorType> & { total?: number; pageParam?: number; meta?: any;};type UseInfiniteGetListOptions
type UseInfiniteGetListOptions< RecordType extends RaRecord = any, ErrorType = Error> = Omit< UseInfiniteQueryOptions< GetInfiniteListResult<RecordType>, ErrorType, InfiniteData<GetInfiniteListResult<RecordType>>, QueryKey, number >, | 'queryKey' | 'queryFn' | 'getNextPageParam' | 'getPreviousPageParam' | 'initialPageParam'> & { onSuccess?: (data: InfiniteData<GetInfiniteListResult<RecordType>>) => void; onError?: (error: ErrorType) => void; onSettled?: ( data?: InfiniteData<GetInfiniteListResult<RecordType>>, error?: ErrorType | null ) => void;};type UseInputValue
type UseInputValue = { id: string; isRequired: boolean; field: Omit<ControllerRenderProps, 'onBlur'> & { onBlur: (event?: FocusEvent<HTMLElement> | EditorEvents['blur']) => void; }; formState: UseFormStateReturn<Record<string, string>>; fieldState: ControllerFieldState;};type UseIsAuthPendingParams
type UseIsAuthPendingParams = { resource?: string; action: HintedString<'list' | 'create' | 'edit' | 'show' | 'delete'>;};type UseListValue
type UseListValue< RecordType extends RaRecord = any, ErrorType = Error> = ListControllerResult<RecordType, ErrorType>;type UseMutationWithMutationModeOptions
type UseMutationWithMutationModeOptions< ErrorType = Error, TData extends { data?: unknown } = { data?: unknown }, TVariables = unknown> = Omit< UseMutationOptions<TData['data'], ErrorType, Partial<TVariables>>, 'mutationFn'> & { getMutateWithMiddlewares?: ( mutate: MutationFunction<TData, TVariables> ) => (params: TVariables) => Promise<TData>; mutationFn?: MutationFunction<TData, TVariables>; mutationMode?: MutationMode; returnPromise?: boolean; updateCache: <OptionsType extends { mutationMode: MutationMode }>( params: Partial<TVariables>, options: OptionsType, mutationResult: TData['data'] | undefined ) => TData['data']; getQueryKeys: <OptionsType extends { mutationMode: MutationMode }>( params: Partial<TVariables>, options: OptionsType ) => Array<QueryKey>; onUndo?: <OptionsType extends { mutationMode: MutationMode }>( params: Partial<TVariables>, options: OptionsType ) => void;};type UseMutationWithMutationModeResult
type UseMutationWithMutationModeResult< TReturnPromise extends boolean = boolean, ErrorType = Error, TData extends { data?: unknown } = { data?: unknown }, TVariables = unknown> = [ MutationFunctionWithOptions<TReturnPromise, ErrorType, TData, TVariables>, UseMutationResult<TData['data'], ErrorType, Partial<TVariables>, unknown> & { isLoading: boolean; }];type UsePrevNextControllerResult
type UsePrevNextControllerResult = { isFetching: boolean; isLoading: boolean; isPending: boolean; hasPrev: boolean; hasNext: boolean; prevPath: string | undefined; nextPath: string | undefined; index: number | undefined; total: number | undefined; error?: any;};type UserCheck
type UserCheck = (payload: object, pathName: string, routeParams?: object) => void;type UseRecordFromLocationOptions
type UseRecordFromLocationOptions = { searchSource?: string; stateSource?: string;};type UseRecordSelectionArgs
type UseRecordSelectionArgs = | UseRecordSelectionWithResourceArgs | UseRecordSelectionWithNoStoreArgs;type UseRecordSelectionResult
type UseRecordSelectionResult<RecordType extends RaRecord = any> = [ RecordType['id'][], { select: (ids: RecordType['id'][]) => void; unselect: (ids: RecordType['id'][], fromAllStoreKeys?: boolean) => void; toggle: (id: RecordType['id']) => void; clearSelection: (fromAllStoreKeys?: boolean) => void; }];type UserMenuContextValue
type UserMenuContextValue = { /** * Closes the user menu * @see UserMenu */ onClose: () => void;};type useStoreResult
type useStoreResult<T = any> = [ T, (value: T | ((value: T) => void), defaultValue?: T) => void];type UseTranslatableOptions
type UseTranslatableOptions = { defaultLocale?: string; locales: string[];};type UseUniqueOptions
type UseUniqueOptions = { debounce?: number; resource?: string; message?: string; filter?: Record<string, any>;};type UseUpdateManyOptions
type UseUpdateManyOptions< RecordType extends RaRecord = any, MutationError = unknown> = Omit< UseMutationOptions< Array<RecordType['id']>, MutationError, Partial<UseUpdateManyMutateParams<RecordType>> >, 'mutationFn'> & { mutationMode?: MutationMode; returnPromise?: boolean; getMutateWithMiddlewares?: < UpdateFunctionType extends DataProvider['updateMany'] = DataProvider['updateMany'] >( mutate: UpdateFunctionType ) => ( ...Params: Parameters<UpdateFunctionType> ) => ReturnType<UpdateFunctionType>;};type UseUpdateManyResult
type UseUpdateManyResult< RecordType extends RaRecord = any, TReturnPromise extends boolean = boolean, MutationError = unknown> = [ ( resource?: string, params?: Partial<UpdateManyParams<RecordType>>, options?: MutateOptions< Array<RecordType['id']>, MutationError, Partial<UseUpdateManyMutateParams<RecordType>>, unknown > & { mutationMode?: MutationMode; returnPromise?: TReturnPromise } ) => Promise<TReturnPromise extends true ? Array<RecordType['id']> : void>, UseMutationResult< Array<RecordType['id']> | undefined, MutationError, Partial<UpdateManyParams<Partial<RecordType>> & { resource?: string }>, unknown > & { isLoading: boolean }];type UseUpdateOptions
type UseUpdateOptions<RecordType extends RaRecord = any, ErrorType = Error> = Omit< UseMutationOptions< RecordType, ErrorType, Partial<UseUpdateMutateParams<RecordType>> >, 'mutationFn'> & { mutationMode?: MutationMode; returnPromise?: boolean; getMutateWithMiddlewares?: < UpdateFunctionType extends DataProvider['update'] = DataProvider['update'] >( mutate: UpdateFunctionType ) => ( ...Params: Parameters<UpdateFunctionType> ) => ReturnType<UpdateFunctionType>;};type UseUpdateResult
type UseUpdateResult< RecordType extends RaRecord = any, TReturnPromise extends boolean = boolean, ErrorType = Error> = [ UpdateMutationFunction<RecordType, TReturnPromise, ErrorType>, UseMutationResult< RecordType, ErrorType, Partial<UpdateParams<RecordType> & { resource?: string }>, unknown > & { isLoading: boolean }];type ValidateForm
type ValidateForm = (data: FieldValues) => FieldValues | Promise<FieldValues>;type ValidationErrorMessage
type ValidationErrorMessage = string | ValidationErrorMessageWithArgs;type Validator
type Validator = ( value: any, values: any, props: any) => | ValidationErrorMessage | null | undefined | Promise<ValidationErrorMessage | null | undefined>;type ValidUntil
type ValidUntil = Date;Namespaces
namespace fetchUtils
module 'src/dataProvider/fetch.ts' {}Utility function to make HTTP calls. It's similar to the HTML5
fetch(), except it handles JSON decoding and HTTP error codes automatically.Parameter url
the URL to call
Parameter options
the options to pass to the HTTP call
Parameter
options.user the user object, used for the Authorization header
Parameter
options.user.token the token to pass as the Authorization header
Parameter
options.user.authenticated whether the user is authenticated or not (the Authorization header will be set only if this is true)
Parameter
options.headers the headers to pass to the HTTP call
Returns
{Promise} the Promise for a response object containing the following properties: - status: the HTTP status code - headers: the HTTP headers - body: the response body - json: the response body parsed as JSON
variable queryParameters
const queryParameters: any;function createHeadersFromOptions
createHeadersFromOptions: (options: Options) => Headers;function fetchJson
fetchJson: ( url: any, options?: Options) => Promise<{ status: number; headers: Headers; body: string; json: any }>;Utility function to make HTTP calls. It's similar to the HTML5
fetch(), except it handles JSON decoding and HTTP error codes automatically.Parameter url
the URL to call
Parameter options
the options to pass to the HTTP call
Parameter
options.user the user object, used for the Authorization header
Parameter
options.user.token the token to pass as the Authorization header
Parameter
options.user.authenticated whether the user is authenticated or not (the Authorization header will be set only if this is true)
Parameter
options.headers the headers to pass to the HTTP call
Returns
{Promise} the Promise for a response object containing the following properties: - status: the HTTP status code - headers: the HTTP headers - body: the response body - json: the response body parsed as JSON
function flattenObject
flattenObject: (value: any, path?: string[]) => any;namespace testUI
module 'src/test-ui/index.ts' {}variable defaultI18nProvider
const defaultI18nProvider: I18nProvider;Package Files (205)
- src/auth/LogoutOnMount.ts
- src/auth/addRefreshAuthToAuthProvider.ts
- src/auth/addRefreshAuthToDataProvider.ts
- src/auth/convertLegacyAuthProvider.ts
- src/auth/types.ts
- src/auth/useAuthProvider.ts
- src/auth/useAuthState.ts
- src/auth/useAuthenticated.ts
- src/auth/useCanAccess.ts
- src/auth/useCanAccessCallback.ts
- src/auth/useCanAccessResources.ts
- src/auth/useCheckAuth.ts
- src/auth/useGetIdentity.ts
- src/auth/useGetPermissions.ts
- src/auth/useHandleAuthCallback.ts
- src/auth/useIsAuthPending.ts
- src/auth/useLogin.ts
- src/auth/useLogout.ts
- src/auth/useLogoutIfAccessDenied.ts
- src/auth/usePermissions.ts
- src/controller/button/useBulkDeleteController.ts
- src/controller/create/useCreateController.ts
- src/controller/edit/useEditController.ts
- src/controller/field/sanitizeFieldRestProps.ts
- src/controller/field/types.ts
- src/controller/field/useReferenceArrayFieldController.ts
- src/controller/field/useReferenceFieldController.ts
- src/controller/field/useReferenceManyFieldController.ts
- src/controller/input/ArrayInputContext.ts
- src/controller/input/SimpleFormIteratorContext.ts
- src/controller/input/SimpleFormIteratorItemContext.ts
- src/controller/input/referenceDataStatus.ts
- src/controller/input/sanitizeInputRestProps.ts
- src/controller/input/useArrayInput.ts
- src/controller/input/useGetArrayInputNewItemDefaults.ts
- src/controller/input/useReferenceArrayInputController.ts
- src/controller/input/useReferenceInputController.ts
- src/controller/input/useSimpleFormIterator.ts
- src/controller/input/useSimpleFormIteratorItem.ts
- src/controller/list/InfinitePaginationContext.ts
- src/controller/list/queryReducer.ts
- src/controller/list/useFilterContext.ts
- src/controller/list/useInfiniteListController.ts
- src/controller/list/useInfinitePaginationContext.ts
- src/controller/list/useList.ts
- src/controller/list/useListContext.ts
- src/controller/list/useListContextWithProps.ts
- src/controller/list/useListController.ts
- src/controller/list/useListFilterContext.ts
- src/controller/list/useListPaginationContext.ts
- src/controller/list/useListParams.ts
- src/controller/list/useListSortContext.ts
- src/controller/list/useRecordSelection.ts
- src/controller/list/useUnselect.ts
- src/controller/list/useUnselectAll.ts
- src/controller/record/useRecordContext.ts
- src/controller/saveContext/SaveContext.ts
- src/controller/saveContext/useMutationMiddlewares.ts
- src/controller/saveContext/usePickSaveContext.ts
- src/controller/saveContext/useRegisterMutationMiddleware.ts
- src/controller/saveContext/useSaveContext.ts
- src/controller/show/useShowController.ts
- src/controller/useFilterState.ts
- src/controller/usePaginationState.ts
- src/controller/usePrevNextController.ts
- src/controller/useReference.ts
- src/controller/useSortState.ts
- src/core/DefaultTitleContext.ts
- src/core/HasDashboardContext.ts
- src/core/ResourceContext.ts
- src/core/UserMenuContext.ts
- src/core/useGetRecordRepresentation.ts
- src/core/useGetResourceLabel.ts
- src/core/useIsOffline.ts
- src/core/useResourceContext.ts
- src/core/useResourceDefinition.ts
- src/core/useResourceDefinitionContext.ts
- src/core/useResourceDefinitions.ts
- src/core/useUserMenu.ts
- src/core/useWrappedSource.ts
- src/dataProvider/DataProviderContext.ts
- src/dataProvider/HttpError.ts
- src/dataProvider/combineDataProviders.ts
- src/dataProvider/convertLegacyDataProvider.ts
- src/dataProvider/dataFetchActions.ts
- src/dataProvider/defaultDataProvider.ts
- src/dataProvider/fetch.ts
- src/dataProvider/testDataProvider.ts
- src/dataProvider/undo/types.ts
- src/dataProvider/undoableEventEmitter.ts
- src/dataProvider/useCreate.ts
- src/dataProvider/useDataProvider.ts
- src/dataProvider/useDelete.ts
- src/dataProvider/useDeleteMany.ts
- src/dataProvider/useGetList.ts
- src/dataProvider/useGetMany.ts
- src/dataProvider/useGetManyAggregate.ts
- src/dataProvider/useGetManyReference.ts
- src/dataProvider/useGetOne.ts
- src/dataProvider/useGetRecordId.ts
- src/dataProvider/useInfiniteGetList.ts
- src/dataProvider/useIsDataLoaded.ts
- src/dataProvider/useLoading.ts
- src/dataProvider/useMutationWithMutationMode.ts
- src/dataProvider/useRefresh.ts
- src/dataProvider/useUpdate.ts
- src/dataProvider/useUpdateMany.ts
- src/dataProvider/withLifecycleCallbacks.ts
- src/dataTable/DataTableCallbacksContext.ts
- src/dataTable/DataTableColumnFilterContext.ts
- src/dataTable/DataTableColumnRankContext.ts
- src/dataTable/DataTableConfigContext.ts
- src/dataTable/DataTableDataContext.ts
- src/dataTable/DataTableRenderContext.ts
- src/dataTable/DataTableSelectedIdsContext.ts
- src/dataTable/DataTableSortContext.ts
- src/dataTable/DataTableStoreContext.ts
- src/dataTable/types.ts
- src/export/ExporterContext.ts
- src/export/defaultExporter.ts
- src/export/downloadCSV.ts
- src/export/fetchRelatedRecords.ts
- src/export/useBulkExport.ts
- src/form/WarnWhenUnsavedChanges.ts
- src/form/choices/ChoicesContext.ts
- src/form/choices/useChoicesContext.ts
- src/form/groups/FormGroupContext.ts
- src/form/groups/useFormGroup.ts
- src/form/groups/useFormGroupContext.ts
- src/form/groups/useFormGroups.ts
- src/form/useApplyInputDefaultValues.ts
- src/form/useAugmentedForm.ts
- src/form/useFormIsDirty.ts
- src/form/useInput.ts
- src/form/useRecordFromLocation.ts
- src/form/useSuggestions.ts
- src/form/validation/getSimpleValidationResolver.ts
- src/form/validation/setSubmissionErrors.ts
- src/form/validation/useGetValidationErrorMessage.ts
- src/form/validation/useNotifyIsFormInvalid.ts
- src/form/validation/useUnique.ts
- src/form/validation/validate.ts
- src/i18n/I18nContext.ts
- src/i18n/TranslatableContext.ts
- src/i18n/TranslationMessages.ts
- src/i18n/TranslationUtils.ts
- src/i18n/index.ts
- src/i18n/substituteTokens.ts
- src/i18n/useI18nProvider.ts
- src/i18n/useLocales.ts
- src/i18n/useResourceTranslation.ts
- src/i18n/useTranslatable.ts
- src/i18n/useTranslatableContext.ts
- src/i18n/useTranslate.ts
- src/i18n/useTranslateLabel.ts
- src/index.ts
- src/inference/InferredElement.ts
- src/inference/getElementsFromRecords.ts
- src/inference/getValuesFromRecords.ts
- src/inference/inferTypeFromValues.ts
- src/inference/types.ts
- src/notification/CloseNotificationContext.ts
- src/notification/NotificationContext.ts
- src/notification/types.ts
- src/notification/useCloseNotification.ts
- src/notification/useNotificationContext.ts
- src/notification/useNotify.ts
- src/preferences/usePreference.ts
- src/preferences/usePreferenceInput.ts
- src/preferences/usePreferencesEditor.ts
- src/preferences/useSetInspectorTitle.ts
- src/routing/types.ts
- src/routing/useBasename.ts
- src/routing/useCreatePath.ts
- src/routing/useGetPathForRecord.ts
- src/routing/useGetPathForRecordCallback.ts
- src/routing/useRedirect.ts
- src/routing/useResetErrorBoundaryOnLocationChange.ts
- src/routing/useRestoreScrollPosition.ts
- src/routing/useSplatPathBase.ts
- src/store/localStorageStore.ts
- src/store/types.ts
- src/store/useRemoveFromStore.ts
- src/store/useRemoveItemsFromStore.ts
- src/store/useResetStore.ts
- src/store/useStore.ts
- src/store/useStoreContext.ts
- src/test-ui/defaultI18nProvider.ts
- src/test-ui/index.ts
- src/types.ts
- src/util/asyncDebounce.ts
- src/util/escapePath.ts
- src/util/getFieldLabelTranslationArgs.ts
- src/util/getMutationMode.ts
- src/util/hooks.ts
- src/util/mergeRefs.ts
- src/util/removeEmpty.ts
- src/util/removeKey.ts
- src/util/shallowEqual.ts
- src/util/useCheckForApplicationUpdate.ts
- src/util/useDebouncedEvent.ts
- src/util/useEvent.ts
- src/util/useFieldValue.ts
- src/util/useWhyDidYouUpdate.ts
- src/util/warning.ts
Dependencies (8)
Dev Dependencies (22)
Peer Dependencies (6)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ra-core.
- Markdown[](https://www.jsdocs.io/package/ra-core)
- HTML<a href="https://www.jsdocs.io/package/ra-core"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 19807 ms. - Missing or incorrect documentation? Open an issue for this package.
