ra-core
- Version 5.7.4
- Published
- 6.31 MB
- 10 dependencies
- MIT license
Install
npm i ra-core
yarn add ra-core
pnpm add ra-core
Overview
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
Index
Variables
- AddNotificationContext
- AddUndoableMutationContext
- AUTH_CHECK
- AUTH_ERROR
- AUTH_GET_PERMISSIONS
- AUTH_LOGIN
- AUTH_LOGOUT
- AuthContext
- ChoicesContext
- CloseNotificationContext
- CREATE
- CreateContext
- CustomRoutes
- DataProviderContext
- DEFAULT_LOCALE
- defaultDataProvider
- defaultExporter
- DefaultTitleContext
- DefaultTitleContextProvider
- DELETE
- DELETE_MANY
- EditContext
- ExporterContext
- fetchActionsWithArrayOfIdentifiedRecordsResponse
- fetchActionsWithArrayOfRecordsResponse
- fetchActionsWithRecordResponse
- fetchActionsWithTotalResponse
- FieldTitle
- FormGroupContext
- GET_LIST
- GET_MANY
- GET_MANY_REFERENCE
- GET_ONE
- HasDashboardContext
- HasDashboardContextProvider
- HIDE_FILTER
- I18N_CHANGE_LOCALE
- I18N_TRANSLATE
- I18nContext
- InferenceTypes
- InfinitePaginationContext
- injectedProps
- ListContext
- ListFilterContext
- ListPaginationContext
- ListSortContext
- NotificationContext
- PreferenceKeyContext
- PreferencesEditorContext
- PreviousLocationStorageKey
- queryReducer
- reactAdminFetchActions
- RecordContext
- ReferenceFieldContext
- ReferenceFieldContextProvider
- regex
- Resource
- ResourceContext
- ResourceDefinitionContext
- SaveContext
- SET_FILTER
- SET_PAGE
- SET_PER_PAGE
- SET_SORT
- SHOW_FILTER
- ShowContext
- SORT_ASC
- SORT_DESC
- SourceContext
- SourceContextProvider
- StoreContext
- TakeUndoableMutationContext
- TranslatableContext
- undoableEventEmitter
- UPDATE
- UPDATE_MANY
- WithPermissions
Functions
- addRefreshAuthToAuthProvider()
- addRefreshAuthToDataProvider()
- AdminRouter()
- applyCallbacks()
- asyncDebounce()
- Authenticated()
- BasenameContextProvider()
- CanAccess()
- choices()
- ChoicesContextProvider()
- combine2Validators()
- combineDataProviders()
- composeSyncValidators()
- composeValidators()
- convertLegacyAuthProvider()
- convertLegacyDataProvider()
- CoreAdmin()
- CoreAdminContext()
- CoreAdminRoutes()
- CoreAdminUI()
- CreateBase()
- CreateContextProvider()
- CreateController()
- downloadCSV()
- EditBase()
- EditContextProvider()
- EditController()
- email()
- escapePath()
- fetchRelatedRecords()
- FilterLiveForm()
- Form()
- FormDataConsumer()
- FormDataConsumerView()
- FormGroupContextProvider()
- FormGroupsProvider()
- getElementsFromRecords()
- getFieldLabelTranslationArgs()
- getFilterFormValues()
- getFormGroupState()
- getListControllerProps()
- getMutationMode()
- getNumberOrDefault()
- getQuery()
- getRecordForLocale()
- getRecordFromLocation()
- getResourceFieldLabelKey()
- getSelectedReferencesStatus()
- getSimpleValidationResolver()
- getStatusForArrayInput()
- getStatusForInput()
- getStorage()
- getSuggestionsFactory()
- getValuesFromRecords()
- hasCustomParams()
- I18nContextProvider()
- inferTypeFromValues()
- InfiniteListBase()
- isEmpty()
- isRequired()
- ListBase()
- ListContextProvider()
- ListController()
- localStorageStore()
- LogoutOnMount()
- maxLength()
- maxValue()
- memoryStore()
- mergeRefs()
- mergeTranslations()
- minLength()
- minValue()
- NavigateToFirstResource()
- NotificationContextProvider()
- number()
- OptionalRecordContextProvider()
- OptionalResourceContextProvider()
- parseQueryFromLocation()
- PreferenceKeyContextProvider()
- PreferencesEditorContextProvider()
- Ready()
- RecordContextProvider()
- RecordRepresentation()
- ReferenceFieldBase()
- ReferenceInputBase()
- removeDoubleSlashes()
- removeEmpty()
- removeKey()
- required()
- resolveBrowserLocale()
- ResourceContextProvider()
- ResourceDefinitionContextProvider()
- RestoreScrollPosition()
- sanitizeFetchType()
- sanitizeListRestProps()
- SaveContextProvider()
- setSubmissionErrors()
- shallowEqual()
- ShowBase()
- ShowContextProvider()
- ShowController()
- StoreContextProvider()
- StoreSetter()
- substituteTokens()
- testDataProvider()
- testI18nProvider()
- TestMemoryRouter()
- TestTranslationProvider()
- TranslatableContextProvider()
- Translate()
- UndoableMutationsContextProvider()
- useAddNotificationContext()
- useAddUndoableMutation()
- useApplyInputDefaultValues()
- useAugmentedForm()
- useAuthenticated()
- useAuthProvider()
- useAuthState()
- useBasename()
- useCanAccess()
- useCanAccessCallback()
- useCanAccessResources()
- useCheckAuth()
- useCheckForApplicationUpdate()
- useCheckMinimumRequiredProps()
- useChoices()
- useChoicesContext()
- useCloseNotification()
- useCreate()
- useCreateContext()
- useCreateController()
- useCreatePath()
- useDataProvider()
- useDebouncedEvent()
- useDeepCompareEffect()
- useDefaultTitle()
- useDelete()
- useDeleteMany()
- useDeleteWithConfirmController()
- useDeleteWithUndoController()
- useEditContext()
- useEditController()
- useEvent()
- useExpandAll()
- useExpanded()
- useFieldValue()
- useFilterState()
- useFirstResourceWithListAccess()
- useFormGroup()
- useFormGroupContext()
- useFormGroups()
- useGetIdentity()
- useGetList()
- useGetMany()
- useGetManyAggregate()
- useGetManyReference()
- useGetOne()
- useGetPathForRecord()
- useGetPathForRecordCallback()
- useGetPermissions()
- useGetRecordId()
- useGetRecordRepresentation()
- useGetResourceLabel()
- useGetValidationErrorMessage()
- useHandleAuthCallback()
- useHasDashboard()
- useI18nProvider()
- useInfiniteGetList()
- useInfiniteListController()
- useInfinitePaginationContext()
- useInput()
- useIsAuthPending()
- useIsDataLoaded()
- useIsMounted()
- useList()
- useListContext()
- useListContextWithProps()
- useListController()
- useListFilterContext()
- useListPaginationContext()
- useListParams()
- useListSortContext()
- useLoading()
- useLocale()
- useLocales()
- useLocaleState()
- useLogin()
- useLogout()
- useLogoutIfAccessDenied()
- useMutationMiddlewares()
- useNotificationContext()
- useNotify()
- useNotifyIsFormInvalid()
- useOptionalSourceContext()
- usePaginationState()
- usePermissions()
- usePickFilterContext()
- usePickPaginationContext()
- usePickSaveContext()
- usePickSortContext()
- usePreference()
- usePreferenceInput()
- usePreferenceKey()
- usePreferencesEditor()
- usePrevious()
- usePrevNextController()
- useRecordContext()
- useRecordFromLocation()
- useRecordSelection()
- useRedirect()
- useReference()
- useReferenceArrayFieldController()
- useReferenceArrayInputController()
- useReferenceFieldContext()
- useReferenceFieldController()
- useReferenceInputController()
- useReferenceManyFieldController()
- useReferenceOneFieldController()
- useRefresh()
- useRegisterMutationMiddleware()
- useRemoveFromStore()
- useRemoveItemsFromStore()
- useRequireAccess()
- useResetErrorBoundaryOnLocationChange()
- useResetStore()
- useResourceContext()
- useResourceDefinition()
- useResourceDefinitionContext()
- useResourceDefinitions()
- useRestoreScrollPosition()
- useSafeSetState()
- useSaveContext()
- useScrollToTop()
- useSelectAll()
- useSetInspectorTitle()
- useSetLocale()
- useShowContext()
- useShowController()
- useSortState()
- useSourceContext()
- useSplatPathBase()
- useStore()
- useStoreContext()
- useSuggestions()
- useTakeUndoableMutation()
- useTimeout()
- useTrackScrollPosition()
- useTranslatable()
- useTranslatableContext()
- useTranslate()
- useTranslateLabel()
- useUnique()
- useUnselect()
- useUnselectAll()
- useUpdate()
- useUpdateMany()
- useWarnWhenUnsavedChanges()
- useWhyDidYouUpdate()
- useWrappedSource()
- ValidationError()
- warning()
- WarnWhenUnsavedChanges()
- withLifecycleCallbacks()
- WithListContext()
- WithRecord()
Classes
Interfaces
Type Aliases
- AdminChildren
- AnyString
- AuthActionType
- AuthProvider
- AuthRedirectResult
- CatchAllComponent
- CheckAuth
- ChildrenFunction
- ChoicesContextBaseValue
- ChoicesContextValue
- CloseNotificationContextValue
- CoreAdminProps
- CreateMutationFunction
- CreatePathType
- CustomRoutesProps
- DashboardComponent
- DataProvider
- DataProviderMatcher
- DataProviderResult
- Dispatch
- EditControllerResult
- Exporter
- ExtractRecordPaths
- FetchRelatedRecords
- FormDataConsumerRender
- FormFunctions
- FormGroupContextValue
- FormProps
- GetRecordForLocale
- GetResourceLabel
- HintedString
- I18nContextProps
- I18nProvider
- Identifier
- InfiniteListControllerResult
- InfinitePaginationContextValue
- InputProps
- LayoutComponent
- LegacyAuthProvider
- LegacyDataProvider
- LinkToFunctionType
- LinkToType
- ListControllerResult
- ListFilterContextValue
- ListPaginationContextValue
- ListSortContextValue
- LoadingComponent
- Locale
- LoginComponent
- Middleware
- MutationMode
- NavigateToFirstResourceProps
- NotificationContextType
- NotificationType
- OnError
- OnSuccess
- OptionText
- OptionTextElement
- OptionTextFunc
- PossibleInferredElementTypes
- PreferencesEditorContextValue
- RecordPath
- RecordToStringFunction
- RecordValues
- RedirectionSideEffect
- RenderResourcesFunction
- ResourceCallback
- ResourceCallbacks
- ResourceCallbacksValue
- ResourceContextValue
- ResourceDefinitionContextValue
- ResourceDefinitions
- ResourceElement
- SaveHandler
- SaveHandlerCallbacks
- SelectTranslatableLocale
- SetOnSave
- ShowControllerResult
- SourceContextValue
- TitleComponent
- TransformData
- TranslateFunction
- UndoableMutation
- UpdateMutationFunction
- UseAugmentedFormProps
- UseAuthenticatedOptions
- 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
- UsePrevNextControllerResult
- UserCheck
- UseRecordFromLocationOptions
- UseRecordSelectionArgs
- UseRecordSelectionResult
- UseRequireAccessOptions
- UseRequireAccessResult
- UseSelectAllResult
- useStoreResult
- UseTranslatableOptions
- UseUniqueOptions
- UseUpdateManyOptions
- UseUpdateManyResult
- UseUpdateOptions
- UseUpdateResult
- ValidateForm
- ValidationErrorMessage
- Validator
- ValidUntil
Namespaces
Variables
variable AddNotificationContext
const AddNotificationContext: any;
variable AddUndoableMutationContext
const AddUndoableMutationContext: any;
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 AuthContext
const AuthContext: any;
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 CREATE
const CREATE: string;
variable CreateContext
const CreateContext: any;
Context to store the result of the useCreateController() hook.
Use the useCreateContext() hook to read the context. That's what the Create components do in react-admin.
Example 1
import { useCreateController, CreateContextProvider } from 'ra-core';
const Create = props => { const controllerProps = useCreateController(props); return ( <CreateContextProvider value={controllerProps}> ... ); };
variable CustomRoutes
const CustomRoutes: { (_props: CustomRoutesProps): null; raName: string };
This component allows you to provide custom routes to the Admin.
Parameter props
The component props
Parameter
props.children The custom routes.
Parameter
props.noLayout A boolean indicating whether to render the routes outside the Layout. Defaults to false.
Returns
Nothing. This is a configuration component.
variable DataProviderContext
const DataProviderContext: any;
variable DEFAULT_LOCALE
const DEFAULT_LOCALE: string;
variable defaultDataProvider
const defaultDataProvider: DataProvider<string>;
variable defaultExporter
const defaultExporter: Exporter<any>;
variable DefaultTitleContext
const DefaultTitleContext: any;
variable DefaultTitleContextProvider
const DefaultTitleContextProvider: any;
variable DELETE
const DELETE: string;
variable DELETE_MANY
const DELETE_MANY: string;
variable EditContext
const EditContext: any;
Context to store the result of the useEditController() hook.
Use the useEditContext() hook to read the context. That's what the Edit components do in react-admin.
Example 1
import { useEditController, EditContextProvider } from 'ra-core';
const Edit = props => { const controllerProps = useEditController(props); return ( <EditContextProvider value={controllerProps}> ... ); };
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 FieldTitle
const FieldTitle: React.MemoExoticComponent<{ (props: FieldTitleProps): | number | Iterable<React.ReactNode> | React.JSX.Element | null; displayName: 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 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 ListContext
const ListContext: any;
Context to store the result of the useListController() hook.
Use the useListContext() hook to read the context. That's what many List components do in react-admin (e.g. , , ).
{Object} ListControllerProps {Array} 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() {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' {Function} refetch a function for triggering a refetch of the list data
Props {ListControllerResult} value
Parameter
{Props}
Example 1
import { useListController, ListContext } from 'ra-core';
const List = props => { const controllerProps = useListController(props); return ( <ListContext.Provider value={controllerProps}> ... </ListContext.Provider> ); };
See Also
useListController
useListContext
variable ListFilterContext
const ListFilterContext: any;
Context to store the filter part of the useListController() result.
Use the useListFilterContext() hook to read the context. That's what many List components do in react-admin (e.g. , ).
{Object} ListFilterContextValue {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') {string} resource the resource name, deduced from the location. e.g. 'posts'
Props {ListFilterContextValue} value
Parameter
{Props}
Example 1
import { useListController, usePickFilterContext, ListFilterContext } from 'ra-core';
const List = props => { const controllerProps = useListController(props); return ( <ListFilterContext.Provider value={usePickFilterContext(controllerProps)}> ... </ListFilterContext.Provider> ); };
See Also
useListController
useListFilterContext
variable ListPaginationContext
const ListPaginationContext: any;
Context to store the pagination part of the useListController() result.
Use the useListPaginationContext() hook to read the pagination information. That's what List components do in react-admin (e.g. ).
{Object} ListPaginationContextValue {boolean} isLoading boolean that is false until the data is available {integer} total the total number of results for the current filters, excluding pagination. Useful to build the pagination controls. e.g. 23 {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) {Boolean} hasPreviousPage true if the current page is not the first one {Boolean} hasNextPage true if the current page is not the last one
{string} resource the resource name, deduced from the location. e.g. 'posts'
Props {ListPaginationContextValue} value
Parameter
{Props}
Example 1
import { useListController, ListPaginationContext } from 'ra-core';
const List = props => { const controllerProps = useListController(props); return ( <ListPaginationContext.Provider value={controllerProps}> ... </ListPaginationContext.Provider> ); };
See Also
useListController
useListContext
variable ListSortContext
const ListSortContext: any;
Context to store the sort part of the useListController() result.
Use the useListSortContext() hook to read the context. That's what many List components do in react-admin (e.g. ).
{Object} ListSortContextValue {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' }) {string} resource the resource name, deduced from the location. e.g. 'posts'
Props {ListSortContextValue} value
Parameter
{Props}
Example 1
import { useListController, usePickSortContext, ListSortContext } from 'ra-core';
const List = props => { const controllerProps = useListController(props); return ( <ListSortContext.Provider value={usePickSortContext(controllerProps)}> ... </ListSortContext.Provider> ); };
See Also
useListController
useListSortContext
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 PreferenceKeyContext
const PreferenceKeyContext: React.Context<string>;
variable PreferencesEditorContext
const PreferencesEditorContext: React.Context<PreferencesEditorContextValue>;
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 queryReducer
const queryReducer: Reducer<ListParams, ActionTypes>;
This reducer is for the react-router query string.
variable reactAdminFetchActions
const reactAdminFetchActions: string[];
variable RecordContext
const RecordContext: React.Context< RaRecord<Identifier> | Omit<RaRecord<Identifier>, 'id'>>;
Context to store a record.
See Also
RecordContextProvider
useRecordContext
variable ReferenceFieldContext
const ReferenceFieldContext: any;
variable ReferenceFieldContextProvider
const ReferenceFieldContextProvider: any;
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 Resource
const Resource: { (props: ResourceProps): React.JSX.Element; raName: string; registerResource({ create, edit, icon, list, name, options, show, recordRepresentation, hasCreate, hasEdit, hasShow, }: ResourceProps): { name: string; options: import('../types').ResourceOptions | undefined; hasList: boolean; hasCreate: boolean; hasEdit: boolean; hasShow: boolean; icon: React.ComponentType<any> | undefined; recordRepresentation: | string | React.ReactElement<any, string | React.JSXElementConstructor<any>> | import('../types').RecordToStringFunction | undefined; };};
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 ResourceDefinitionContext
const ResourceDefinitionContext: React.Context<ResourceDefinitionContextValue>;
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 ShowContext
const ShowContext: any;
Context to store the result of the useShowController() hook.
Use the useShowContext() hook to read the context. That's what the Show components do in react-admin.
Example 1
import { useShowController, ShowContextProvider } from 'ra-core';
const Show = props => { const controllerProps = useShowController(props); return ( <ShowContextProvider value={controllerProps}> ... ); };
variable SORT_ASC
const SORT_ASC: string;
variable SORT_DESC
const SORT_DESC: string;
variable SourceContext
const SourceContext: any;
Context that provides a function that accept a source and return getters for the modified source and label.
This allows some special inputs to prefix or suffix the source of their children.
Example 1
const sourceContext = { getSource: source =>
coordinates.${source}
, getLabel: source =>resources.posts.fields.${source}
, } const CoordinatesInput = () => { return ( <SourceContextProvider value={sourceContext}> ); };
variable SourceContextProvider
const SourceContextProvider: any;
variable StoreContext
const StoreContext: any;
variable TakeUndoableMutationContext
const TakeUndoableMutationContext: any;
variable TranslatableContext
const TranslatableContext: any;
variable undoableEventEmitter
const undoableEventEmitter: EventEmitter<string | symbol, any>;
variable UPDATE
const UPDATE: string;
variable UPDATE_MANY
const UPDATE_MANY: string;
variable WithPermissions
const WithPermissions: React.ComponentType<WithPermissionsProps>;
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 AdminRouter
AdminRouter: ({ basename, children }: AdminRouterProps) => React.JSX.Element;
Creates a react-router Router unless the app is already inside existing router. Also creates a BasenameContext with the basename prop
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 Authenticated
Authenticated: ( props: AuthenticatedProps) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null;
Restrict access to children to authenticated users. Redirects anonymous users to the login page.
Use it to decorate your custom page components to require authentication.
Example 1
import { Admin, CustomRoutes, Authenticated } from 'react-admin';
const customRoutes = [ <Route path="/foo" element={ <Authenticated authParams={{ foo: 'bar' }}> } /> ]; const App = () => ( {customRoutes} );
See Also
useAuthState
function BasenameContextProvider
BasenameContextProvider: ({ children, basename,}: { children: any; basename: any;}) => React.JSX.Element;
Set the string to append to all links to the admin app.
Useful when the app is mounted on a sub path, e.g. '/admin'. Used internally by the
<Admin>
component.See Also
useBasename
function CanAccess
CanAccess: < RecordType extends | RaRecord<Identifier> | Omit<RaRecord<Identifier>, 'id'> = RaRecord<Identifier>, ErrorType extends Error = Error>({ children, loading, accessDenied, error: errorElement, ...props}: CanAccessProps<RecordType, ErrorType>) => React.ReactNode;
A component that only displays its children after checking whether users are authorized to access the provided resource and action.
Parameter options
Parameter
options.action The action to check. One of 'list', 'create', 'edit', 'show', 'delete', or a custom action.
Parameter
options.resource The resource to check. e.g. 'posts', 'comments', 'users'
Parameter
options.children The component to render if users are authorized.
Parameter
options.loading An optional element to render while the authorization is being checked. Defaults to null.
Parameter
options.accessDenied An optional element to render if users are denied access. Defaults to null.
Parameter
options.error An optional element to render if an error occur while checking users access rights. Redirect users to
/authentication-error
by default.
function choices
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} />
function ChoicesContextProvider
ChoicesContextProvider: ({ children, value,}: { children: ReactNode; value: ChoicesContextValue;}) => React.JSX.Element;
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 | null | undefined> | undefined;
function composeValidators
composeValidators: (...validators: any[]) => Validator;
function convertLegacyAuthProvider
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
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 CoreAdmin
CoreAdmin: (props: CoreAdminProps) => React.JSX.Element;
Main admin component, entry point to the application.
Initializes the various contexts (auth, data, i18n, router) and defines the main routes.
Expects a list of resources as children, or a function returning a list of resources based on the permissions.
Example 1
// static list of resources
import { CoreAdmin, Resource, ListGuesser, useDataProvider, } from 'ra-core';
const App = () => ( <CoreAdmin dataProvider={myDataProvider}> <Resource name="posts" list={ListGuesser} /> );
// dynamic list of resources based on permissions
import { CoreAdmin, Resource, ListGuesser, useDataProvider, } from 'ra-core';
const App = () => ( <CoreAdmin dataProvider={myDataProvider}> {permissions => [ <Resource name="posts" key="posts" list={ListGuesser} />, ]} );
// If you have to build a dynamic list of resources using a side effect, // you can't use . But as it delegates to sub components, // it's relatively straightforward to replace it:
import * as React from 'react'; import { useEffect, useState } from 'react'; import { CoreAdminContext, CoreAdminUI, Resource, ListGuesser, useDataProvider, } from 'ra-core';
const App = () => ( <CoreAdminContext dataProvider={myDataProvider}> );
const UI = () => { const [resources, setResources] = useState([]); const dataProvider = useDataProvider(); useEffect(() => { dataProvider.introspect().then(r => setResources(r)); }, []);
return ( {resources.map(resource => ( <Resource name={resource.name} key={resource.key} list={ListGuesser} /> ))} ); };
function CoreAdminContext
CoreAdminContext: (props: CoreAdminContextProps) => React.JSX.Element;
function CoreAdminRoutes
CoreAdminRoutes: (props: CoreAdminRoutesProps) => React.JSX.Element;
function CoreAdminUI
CoreAdminUI: (props: CoreAdminUIProps) => React.JSX.Element;
function CreateBase
CreateBase: < RecordType extends Omit<RaRecord<Identifier>, 'id'> = any, ResultRecordType extends RaRecord<Identifier> = RecordType & { id: Identifier }, MutationOptionsError = Error>({ children, loading, ...props}: CreateBaseProps<RecordType, ResultRecordType, MutationOptionsError>) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null;
Call useCreateController and put the value in a CreateContext
Base class for components, without UI.
Accepts any props accepted by useCreateController: - id: The record identifier - resource: The resource
Example 1
// Custom edit layout
const PostCreate = () => ( <Grid container> <Grid item xs={8}> ... <Grid item xs={4}> Create instructions... Post related links... );
function CreateContextProvider
CreateContextProvider: ({ children, value,}: { children: ReactNode; value: CreateControllerResult;}) => React.JSX.Element;
Create a Create Context.
Example 1
const MyCreate = (props) => { const controllerProps = useCreateController(props); return ( <CreateContextProvider value={controllerProps}> ); };
const MyCreateView = () => { const record = useRecordContext(); // or, to rerender only when the save operation change but not data const { saving } = useCreateContext(); }
See Also
CreateContext
RecordContext
function CreateController
CreateController: < RecordType extends Omit<RaRecord<Identifier>, 'id'> = any, MutationOptionsError = Error>({ children, ...props}: { children: (params: CreateControllerResult<RecordType>) => ReactNode;} & CreateControllerProps< RecordType, MutationOptionsError, RecordType & { id: import('../../types').Identifier }>) => ReactNode;
Render prop version of the useCreateController hook
Example 1
const CreateView = () => ... const MyCreate = props => ( <CreateController {...props}> {controllerProps => <CreateView {...controllerProps} {...props} />} );
See Also
useCreateController
function downloadCSV
downloadCSV: (csv: string, filename?: string) => void;
function EditBase
EditBase: <RecordType extends RaRecord<Identifier> = any, ErrorType = Error>({ children, loading, ...props}: EditBaseProps<RecordType, ErrorType>) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null;
Call useEditController and put the value in a EditContext
Base class for components, without UI.
Accepts any props accepted by useEditController: - id: The record identifier - resource: The resource
Example 1
// Custom edit layout
const PostEdit = () => ( <Grid container> <Grid item xs={8}> ... <Grid item xs={4}> Edit instructions... Post related links... );
function EditContextProvider
EditContextProvider: ({ children, value,}: { children: ReactNode; value: EditControllerResult<any, any>;}) => React.JSX.Element;
Create an Edit Context.
Example 1
const MyEdit = (props) => { const controllerProps = useEditController(props); return ( <EditContextProvider value={controllerProps}> ); };
const MyEditView = () => { const record = useRecordContext(); // or, to rerender only when the save operation change but not data const { saving } = useEditContext(); }
See Also
EditContext
RecordContext
function EditController
EditController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>({ children, ...props}: { children: (params: EditControllerResult<RecordType, ErrorType>) => ReactNode;} & EditControllerProps<RecordType, ErrorType>) => ReactNode;
Render prop version of the useEditController hook
Example 1
const EditView = () => ... const MyEdit = props => ( <EditController {...props}> {controllerProps => <EditView {...controllerProps} {...props} />} );
See Also
useEditController
function email
email: ( message?: any) => (value: any, values?: any) => string | { message: string; args: 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} />
function escapePath
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
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 FilterLiveForm
FilterLiveForm: (props: FilterLiveFormProps) => React.JSX.Element;
This component offers a convenient way to create a form that automatically updates the filters when the user changes its child input values.
It fits nicely alongside a
<FilterList>
component, but you can also use it at other places to create your own filter UI.Example 1
import MailIcon from '@mui/icons-material/MailOutline'; import TitleIcon from '@mui/icons-material/Title'; import { Card, CardContent } from '@mui/material'; import * as React from 'react'; import { FilterLiveForm, FilterList, FilterListItem, FilterListSection, TextInput, } from 'react-admin';
export const BookListAside = () => ( <Card sx={{ order: -1, mr: 2, mt: 6, width: 250, height: 'fit-content' }}> <FilterList label="Subscribed to newsletter" icon={}> <FilterListItem label="Yes" value={{ has_newsletter: true }} /> <FilterListItem label="No" value={{ has_newsletter: false }} /> <FilterListSection label="Title" icon={}> <TextInput source="title" resettable helperText={false} /> );
function Form
Form: <RecordType = any>(props: FormProps<RecordType>) => React.JSX.Element;
Creates a form element, initialized with the current record, calling the saveContext on submit
Wrapper around react-hook-form's useForm, FormContextProvider, and . Also sets up a FormGroupContext, and handles submission validation.
Example 1
const MyForm = ({ record, defaultValues, validate }) => ( <Form record={record} defaultValues={defaultValues} validate={validate}> );
{Object} Props the props you can use {Object} defaultValues {Function} validate {Function} save
See Also
useForm
FormGroupContext
https://react-hook-form.com/docs/useformcontext
function FormDataConsumer
FormDataConsumer: <TFieldValues extends FieldValues = FieldValues>( props: ConnectedProps<TFieldValues>) => React.JSX.Element;
Get the current (edited) value of the record from the form and pass it to a child function
Example 1
const PostEdit = () => ( <SimpleForm> {({ formData }) => formData.hasEmail && } );
Example 2
const OrderEdit = () => ( <SelectInput source="country" choices={countries} /> <FormDataConsumer> {({ formData }) => <SelectInput source="city" choices={getCitiesFor(formData.country)} /> } );
function FormDataConsumerView
FormDataConsumerView: <TFieldValues extends FieldValues = FieldValues>( props: Props<TFieldValues>) => any;
function FormGroupContextProvider
FormGroupContextProvider: ({ children, name,}: { children: ReactNode; name: string;}) => React.JSX.Element;
This provider allows its input children 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).
Parameter props
The component props
Parameter
{ReactNode} props.children The form group content
Parameter
{String} props.name The form group name
Example 1
import { Edit, SimpleForm, TextInput, FormGroupContextProvider, useFormGroup } from 'react-admin'; import { Accordion, AccordionDetails, AccordionSummary, Typography } from '@mui/material';
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.invalid && formGroupState.dirty ? 'error' : 'inherit'}> {children} ); }
function FormGroupsProvider
FormGroupsProvider: ({ children }: { children: ReactNode }) => React.JSX.Element;
This component provides functions through context to manage form groups, allowing to link or unlink an input to a group.
See Also
FormGroupContextProvider
useFormGroup
useFormGroups
function getElementsFromRecords
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); // [ // , // , // , // , // ];
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 getFilterFormValues
getFilterFormValues: ( formValues: Record<string, any>, filterValues: Record<string, any>) => {};
Because we are using controlled inputs with react-hook-form, we must provide a default value for each input when resetting the form. (see https://react-hook-form.com/docs/useform/reset). To ensure we don't provide undefined which will result to the current input value being reapplied and due to the dynamic nature of the filter form, we rebuild the filter form values from its current values and make sure to pass at least an empty string for each input.
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) => {} | undefined;
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 | undefined; stateSource?: string | undefined }) => 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 | null; warning: string | null; choices: RecordType[];};
function getStatusForInput
getStatusForInput: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>>({ field, matchingReferences, referenceRecord, translate,}: GetStatusForInputParams<RecordType>) => { waiting: any; error: string | null; warning: string | null; choices: RecordType[];};
function getStorage
getStorage: () => LocalStorageShim | Storage;
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 getValuesFromRecords
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], // }
function hasCustomParams
hasCustomParams: (params: ListParams) => any;
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 I18nContextProvider
I18nContextProvider: ({ value, children,}: I18nContextProviderProps) => React.JSX.Element | null;
Store the i18nProvider in a context, and rerender children when the locale changes
function inferTypeFromValues
inferTypeFromValues: (name: any, values?: never[]) => 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 InfiniteListBase
InfiniteListBase: <RecordType extends RaRecord<Identifier> = any>({ children, loading, ...props}: InfiniteListBaseProps<RecordType>) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null;
Call useInfiniteListController and put the value in a ListContext
Base class for components, without UI.
Accepts any props accepted by useInfiniteListController: - filter: permanent filter applied to the list - filters: Filter element, to display the filters - filterDefaultValues: object; - perPage: Number of results per page - sort: Default sort - exporter: exported function
Example 1
// Custom list layout
const PostList = () => ( <InfiniteListBase perPage={10}> List metrics... <Grid container> <Grid item xs={8}> <SimpleList primaryText={record => record.title} /> <Grid item xs={4}> List instructions... Post related links... );
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 ListBase
ListBase: <RecordType extends RaRecord<Identifier> = any>({ children, loading, ...props}: ListBaseProps<RecordType>) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null;
Call useListController and put the value in a ListContext
Base class for components, without UI.
Accepts any props accepted by useListController: - filter: permanent filter applied to the list - filters: Filter element, to display the filters - filterDefaultValues: object; - perPage: Number of results per page - sort: Default sort - exporter: exported function
Example 1
// Custom list layout
const PostList = () => ( <ListBase perPage={10}> List metrics... <Grid container> <Grid item xs={8}> <SimpleList primaryText={record => record.title} /> <Grid item xs={4}> List instructions... Post related links... );
function ListContextProvider
ListContextProvider: ({ value, children,}: { value: ListControllerResult; children: React.ReactNode;}) => React.JSX.Element;
Create a List Context and several thematic List subcontext.
Allows children to subscribe to part of the ListContext, and bail out of rendering when some parts of the context that they don't depend on change (because unfortunately React doesn't allow to use context selectors yet).
Example 1
const MyList = (props) => { const controllerProps = useListController(props); return ( <ListContextProvider value={controllerProps}> ); };
const MyListView = () => { const { data, filterValues, setFilters } = useListContext(); // or, to rerender only when filters change but not data const { filterValues, setFilters } = useListFilterContext(); }
See Also
ListContext
ListFilterContext
function ListController
ListController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>({ children, ...props}: { children: (params: ListControllerResult<RecordType, ErrorType>) => ReactNode;} & ListControllerProps<RecordType, ErrorType>) => ReactNode;
Render prop version of the useListController hook.
Example 1
const ListView = () => ...; const List = props => ( <ListController {...props}> {controllerProps => <ListView {...controllerProps} {...props} />} )
See Also
useListController
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: () => null;
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 maxLength
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} />
function maxValue
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} />
function memoryStore
memoryStore: (storage?: any) => Store;
Store using memory
Example 1
import { memoryStore } from 'react-admin';
const App = () => ( <Admin store={memoryStore()}> ... );
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 minLength
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} />
function minValue
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} />
function NavigateToFirstResource
NavigateToFirstResource: ({ loading: LoadingPage,}: NavigateToFirstResourceProps) => React.JSX.Element | undefined;
This component will inspect the registered resources and navigate to the first one for which users have access to the list page.
Parameter props
Parameter
props.loading The component to display while the component is loading.
function NotificationContextProvider
NotificationContextProvider: ({ children,}: { children: any;}) => React.JSX.Element;
function number
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} />
function OptionalRecordContextProvider
OptionalRecordContextProvider: < RecordType extends | RaRecord<Identifier> | Omit<RaRecord<Identifier>, 'id'> = RaRecord<Identifier>>({ value, children,}: { children: ReactElement; value?: RecordType;}) => React.JSX.Element;
Wrap children with a RecordContext provider only if the value is defined.
Allows a component to work outside of a record context.
Example 1
import { OptionalRecordContextProvider, TextField } from 'react-admin';
const RecordTitle = ({ record }) => ( <OptionalRecordContextProvider value={record}> );
function OptionalResourceContextProvider
OptionalResourceContextProvider: ({ value, children,}: { value?: ResourceContextValue; children: ReactElement;}) => React.JSX.Element;
Wrap children with a ResourceContext provider only if the value is defined.
Allows a component to work outside of a resource context.
Example 1
import { OptionalResourceContextProvider, EditButton } from 'react-admin';
const Button = ({ resource }) => ( <OptionalResourceContextProvider value={resource}> );
function parseQueryFromLocation
parseQueryFromLocation: ({ search }: { search: any }) => Partial<ListParams>;
function PreferenceKeyContextProvider
PreferenceKeyContextProvider: ({ value, children,}: { value?: string | null | undefined; children: React.ReactNode;}) => React.JSX.Element;
function PreferencesEditorContextProvider
PreferencesEditorContextProvider: ({ children,}: { children: any;}) => React.JSX.Element;
function Ready
Ready: () => React.JSX.Element;
function RecordContextProvider
RecordContextProvider: < RecordType extends | RaRecord<Identifier> | Omit<RaRecord<Identifier>, 'id'> = RaRecord<Identifier>>({ children, value,}: RecordContextProviderProps<RecordType>) => React.JSX.Element;
Provider for the Record Context, to store a record.
Use the useRecordContext() hook to read the context. That's what the Edit and Show components do in react-admin.
Many react-admin components read the RecordContext, including all Field components.
Example 1
import { useGetOne, RecordContextProvider } from 'ra-core';
const Show = ({ resource, id }) => { const { data } = useGetOne(resource, { id }); return ( <RecordContextProvider value={data}> ... ); };
function RecordRepresentation
RecordRepresentation: (props: { record?: RaRecord<import('../../types').Identifier> | undefined; resource?: string | undefined;}) => React.JSX.Element;
Render the record representation as specified on its parent .
Parameter props
The component props
Parameter
{string} props.resource The resource name
Parameter
{RaRecord} props.record The record to render
function ReferenceFieldBase
ReferenceFieldBase: < ReferenceRecordType extends RaRecord<Identifier> = RaRecord<Identifier>>( props: ReferenceFieldBaseProps<ReferenceRecordType>) => React.JSX.Element;
Fetch reference record, and render its representation, or delegate rendering to child component.
The reference prop should be the name of one of the components added as child.
Example 1
// using recordRepresentation
Example 2
// using a Field component to represent the record
Example 3
// By default, includes a link to the page of the related record // (
/users/:userId
in the previous example). // Set thelink
prop to "show" to link to the page instead.Example 4
// You can also prevent
<ReferenceFieldBase>
from adding link to children // by settinglink
to false. <ReferenceFieldBase label="User" source="userId" reference="users" link={false} />Example 5
// Alternatively, you can also pass a custom function to
link
. // It must take reference and record as arguments and return a string <ReferenceFieldBase label="User" source="userId" reference="users" link={(record, reference) => "/path/to/${reference}/${record}"} />In previous versions of React-Admin, the prop
linkType
was used. It is now deprecated and replaced withlink
. However backward-compatibility is still kept
function ReferenceInputBase
ReferenceInputBase: (props: ReferenceInputBaseProps) => React.JSX.Element;
An Input component for choosing a reference record. Useful for foreign keys.
This component fetches the possible values in the reference resource (using
dataProvider.getList()
), and renders the child you passed to which it passes the possible choices via aChoicesContext
.You must pass a child selection component to customize the way the reference selector is displayed (e.g. using
<SelectInput>
or<RadioButtonGroupInput>
instead of<AutocompleteInput>
).Note that the child component should handle the error and loading cases as this base component does not.
Example 1
// using a SelectInput as selector export const CommentEdit = () => ( );
By default, restricts the possible values to 25. You can extend this limit by setting the
perPage
prop.Example 2
<ReferenceInputBase source="post_id" reference="posts" perPage={100}/>
By default, orders the possible values by id desc. You can change this order by setting the
sort
prop (an object withfield
andorder
properties).Example 3
<ReferenceInputBase source="post_id" reference="posts" sort={{ field: 'title', order: 'ASC' }} >
Also, you can filter the query used to populate the possible values. Use the
filter
prop for that.Example 4
<ReferenceInputBase source="post_id" reference="posts" filter={{ is_published: true }} >
The enclosed component may filter results. ReferenceInputBase create a ChoicesContext which provides a
setFilters
function. You can call this function to filter the results.
function removeDoubleSlashes
removeDoubleSlashes: (path: string) => string;
function removeEmpty
removeEmpty: (object: any) => {};
function removeKey
removeKey: (target: any, path: any) => any;
function required
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} />
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 ResourceContextProvider
ResourceContextProvider: ({ children, value,}: { children: ReactNode; value?: ResourceContextValue;}) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null | undefined;
Create a Resource Context with the resource name
Some react-admin components rely on the resource name to be available in the context. This component provides it.
If the value is empty, the context is not provided.
Parameter value
the resource name
Example 1
import { ResourceContextProvider } from 'react-admin';
const MyComponent = () => ( );
function ResourceDefinitionContextProvider
ResourceDefinitionContextProvider: ({ definitions: defaultDefinitions, children,}: { definitions?: ResourceDefinitions<any> | undefined; children: AdminChildren;}) => React.JSX.Element;
Context to store the current resource Definition.
Use the useResourceDefinition() hook to read the context.
Example 1
import { useResourceDefinition, useTranslate } from 'ra-core';
const PostMenuItem = () => { const { name, icon } = useResourceDefinition({ resource: 'posts' });
return ( {icon} {name} ); };
function RestoreScrollPosition
RestoreScrollPosition: ({ children, storeKey, debounce,}: { storeKey: string; debounce?: number | undefined; children: ReactNode;}) => ReactNode;
A component that tracks the scroll position and restores it when the component mounts.
Parameter children
The content to render
Parameter key
The key under which to store the scroll position in the store
Parameter debounceMs
The debounce time in milliseconds
Example 1
import { RestoreScrollPosition } from 'ra-core';
const MyCustomPage = () => { My Custom Page };
function sanitizeFetchType
sanitizeFetchType: (fetchType: string) => string;
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 SaveContextProvider
SaveContextProvider: ({ children, value,}: { children: any; value: any;}) => React.JSX.Element;
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 ShowBase
ShowBase: <RecordType extends RaRecord<Identifier> = any>({ children, loading, ...props}: ShowBaseProps<RecordType>) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null;
Call useShowController and put the value in a ShowContext
Base class for components, without UI.
Accepts any props accepted by useShowController: - id: The record identifier - resource: The resource
Example 1
// Custom show layout
const PostShow = () => ( <Grid container> <Grid item xs={8}> ... <Grid item xs={4}> Show instructions... Post related links... );
function ShowContextProvider
ShowContextProvider: ({ children, value,}: { children: ReactNode; value: ShowControllerResult;}) => React.JSX.Element;
Create a Show Context.
Example 1
const MyShow = (props) => { const controllerProps = useShowController(props); return ( <ShowContextProvider value={controllerProps}> ); };
const MyShowView = () => { const record = useRecordContext(); }
See Also
ShowContext
RecordContext
function ShowController
ShowController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>({ children, ...props}: { children: (params: ShowControllerResult<RecordType, ErrorType>) => ReactNode;} & ShowControllerProps<RecordType, ErrorType>) => ReactNode;
Render prop version of the useShowController hook
Example 1
const ShowView = () => ... const MyShow = () => ( {controllerProps => <ShowView {...controllerProps} {...props} />} );
See Also
useShowController
function StoreContextProvider
StoreContextProvider: ({ value: Store, children,}: StoreContextProviderProps) => React.JSX.Element;
function StoreSetter
StoreSetter: ({ value, name, children }: StoreSetterProps) => React.JSX.Element;
A component to set store state for a key on mount declaratively
To use it, just wrap any component that need to use the corresponding store item with . This wrapping needs to be done to ensure that the corresponding store item is set before rendering the wrapped component.
Tip: is a great helper for mocking the store in unit tests. Prefer it to calling the Store manually.
Parameter props
Parameter
{string} props.name Store item key. Required. Separate with dots to namespace, e.g. 'posts.list.columns'
Parameter
{any} props.value Store item value. Required.
Parameter
{children} props.children Children are rendered as is, on mount
Example 1
Example 2
// Using is equivalent to using
useStoreContext
and setting its value directly.const [, setDensity] = useStore('list.density');
useEffect(() => { setDensity('small'); }, []);
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 testI18nProvider
testI18nProvider: ({ translate, messages,}?: { translate?: import('../types').TranslateFunction | undefined; messages?: IMessages | undefined;}) => I18nProvider;
function TestMemoryRouter
TestMemoryRouter: ({ children, locationCallback, navigateCallback, ...rest}: { children: React.ReactNode; locationCallback?: (l: Location) => void; navigateCallback?: (n: NavigateFunction) => void; basename?: string | undefined; initialEntries?: InitialEntry[] | undefined; initialIndex?: number | undefined;}) => React.JSX.Element;
Wrapper around react-router's
createMemoryRouter
to be used in test components.It is similar to
MemoryRouter
but it supports [data APIs](https://reactrouter.com/en/main/routers/picking-a-router#data-apis).Additionally, it provides - a
locationCallback
prop to get the location in the test - anavigateCallback
prop to be able to navigate in the test
function TestTranslationProvider
TestTranslationProvider: ({ translate, messages, children,}: any) => React.JSX.Element;
function TranslatableContextProvider
TranslatableContextProvider: ({ children, value,}: { children: ReactNode; value: TranslatableContextValue;}) => ReactElement;
function Translate
Translate: ({ i18nKey, options, children,}: TranslateProps) => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null | undefined;
function UndoableMutationsContextProvider
UndoableMutationsContextProvider: ({ children,}: { children: any;}) => React.JSX.Element;
Exposes and manages a queue of undoable mutations
This context is used in CoreAdminContext so that every react-admin app can use the useAddUndoableMutation and useTakeUndoableMutation hooks.
Note: We need a separate queue for mutations (instead of using the notifications queue) because the mutations are not dequeued when the notification is displayed, but when it is dismissed.
function useAddNotificationContext
useAddNotificationContext: () => ( notification: import('./types').NotificationPayload) => void;
function useAddUndoableMutation
useAddUndoableMutation: () => ( mutation: import('./types').UndoableMutation) => void;
function useApplyInputDefaultValues
useApplyInputDefaultValues: ({ inputProps, isArrayInput, fieldArrayInputControl,}: Props) => void;
function useAugmentedForm
useAugmentedForm: <RecordType = any>( props: UseAugmentedFormProps<RecordType>) => { form: any; handleSubmit: (values: any, event: any) => Promise<void>; formHandleSubmit: (event: BaseSyntheticEvent) => void;};
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>) => import('./useAuthState').UseAuthStateResult<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
authParams
at 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: () => string;
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 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>, unknown >, 'mutationFn' >) => UseMutateAsyncFunction< boolean, ErrorType, UseCanAccessCallbackOptions<Record<string, any>>, unknown>;
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.
useCanAccessResources
returns 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 useCheckMinimumRequiredProps
useCheckMinimumRequiredProps: ( displayName: string, requiredProps: string[], props: any) => void;
function useChoices
useChoices: ({ optionText, optionValue, disableValue, translateChoice,}: UseChoicesOptions) => { getChoiceText: (choice: any) => string | React.JSX.Element; getChoiceValue: (choice: any) => any; getDisableValue: (choice: any) => any;};
function useChoicesContext
useChoicesContext: < ChoicesType extends RaRecord<Identifier> = RaRecord<Identifier>>( options?: Partial<ChoicesContextValue<any>> & { choices?: ChoicesType[] }) => ChoicesContextValue<ChoicesType>;
function useCloseNotification
useCloseNotification: () => import('./CloseNotificationContext').CloseNotificationContextValue;
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 useCreateContext
useCreateContext: < RecordType extends RaRecord<Identifier> = RaRecord<Identifier>>() => CreateControllerResult<RecordType>;
Hook to read the create controller props from the CreateContext.
Used within a (e.g. as a descendent of ).
Returns
{CreateControllerResult} create controller props
See Also
useCreateController for how it is filled
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: () => ({ resource, id, type }: CreatePathParams) => string;
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 useDebouncedEvent
useDebouncedEvent: <Args extends unknown[], Return>( callback: (...args: Args) => Return, delay: number) => (...args: Args) => Return;
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: () => TitleComponent;
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?: any) => UseDeleteResult<RecordType, MutationError>;
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?: any) => UseDeleteManyResult<RecordType, MutationError>;
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 useDeleteWithConfirmController
useDeleteWithConfirmController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props: UseDeleteWithConfirmControllerParams<RecordType, ErrorType>) => UseDeleteWithConfirmControllerReturn;
Prepare a set of callbacks for a delete button guarded by confirmation dialog
Example 1
const DeleteButton = ({ resource, record, redirect, onClick, ...rest }) => { const { open, isPending, handleDialogOpen, handleDialogClose, handleDelete, } = useDeleteWithConfirmController({ resource, record, redirect, onClick, });
return ( <Button onClick={handleDialogOpen} label="ra.action.delete" {...rest} > {icon} <Confirm isOpen={open} loading={isPending} title="ra.message.delete_title" content="ra.message.delete_content" translateOptions={{ name: resource, id: record.id, }} onConfirm={handleDelete} onClose={handleDialogClose} /> ); };
function useDeleteWithUndoController
useDeleteWithUndoController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props: UseDeleteWithUndoControllerParams<RecordType, ErrorType>) => UseDeleteWithUndoControllerReturn;
Prepare callback for a Delete button with undo support
Example 1
import React from 'react'; import ActionDelete from '@mui/icons-material/Delete'; import { Button, useDeleteWithUndoController } from 'react-admin';
const DeleteButton = ({ resource, record, redirect, onClick, ...rest }) => { const { isPending, handleDelete } = useDeleteWithUndoController({ resource, record, redirect, onClick, });
return ( <Button onClick={handleDelete} disabled={isPending} label="ra.action.delete" {...rest} > ); };
function useEditContext
useEditContext: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>() => EditControllerResult<RecordType, ErrorType>;
Hook to read the edit controller props from the EditContext.
Used within a (e.g. as a descendent of ).
Returns
{EditControllerResult} edit controller props
See Also
useEditController for how it is filled
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 useExpandAll
useExpandAll: (resource: string, ids: Identifier[]) => [boolean, () => void];
State-like hook for controlling the expanded state of many list items expanded state is true when at least one item from ids is expanded.
Parameter resource
The resource name, e.g. 'posts'
Parameter ids
A list of record identifiers
Returns
{Object} Destructure as [expanded, toggleExpanded].
Example 1
const [expanded, toggleExpanded] = useExpandAll('posts', [123, 124, 125]); const expandIcon = expanded ? ExpandLess : ExpandMore; const onExpandClick = () => toggleExpanded();
function useExpanded
useExpanded: ( resource: string, id: Identifier, single?: boolean) => [boolean, () => void];
State-like hook for controlling the expanded state of a list item
Parameter resource
The resource name, e.g. 'posts'
Parameter id
The record identifier, e.g. 123
Parameter single
Forces only one id to be expanded at a time
Returns
{Object} Destructure as [expanded, toggleExpanded].
Example 1
const [expanded, toggleExpanded] = useExpanded('posts', 123); const expandIcon = expanded ? ExpandLess : ExpandMore; const onExpandClick = () => toggleExpanded();
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 useFilterState
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' }
function useFirstResourceWithListAccess
useFirstResourceWithListAccess: () => { resource: string | undefined; isPending: boolean;};
A hook that returns the first resource for which users have access to the list page. It calls the
authProvider.canAccess
if available to check the permissions.
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: () => string | null;
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: () => | import('./FormGroupsContext').FormGroupsContextValue | undefined;
Retrieve the form groups management context. Used by inputs to register themselves into a form group.
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) => ( params: UseGetRouteForRecordOptions<RecordType>) => Promise<string | false | undefined>;
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
.recordId
is obtained from parameters if passed as a parameter, or from theRecordContext
if 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
recordId
determined in this manner.Example 1
const recordId = useGetRecordId();
function useGetRecordRepresentation
useGetRecordRepresentation: (resource?: string) => (record: any) => ReactNode;
Get default string representation of a record
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
Resource
component 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 theredirectTo
location returned byauthProvider. handleCallback
.Returns
An object containing { isPending, data, error, refetch }.
function useHasDashboard
useHasDashboard: () => boolean;
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: () => import('..').I18nProvider;
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 | undefined }) => boolean;
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 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 useLocale
useLocale: () => string;
Get the current locale
Example 1
import { useLocale } from 'react-admin';
const availableLanguages = { en: 'English', fr: 'Français', } const CurrentLanguage = () => { const locale = useLocale(); return {availableLanguages[locale]}; }
function useLocales
useLocales: (options?: UseLocalesOptions) => { locale: string; name: string }[];
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 useLocaleState
useLocaleState: () => import('../store/useStore').useStoreResult<string>;
Get the current locale and the ability to change it
Example 1
import { useLocaleState } from 'react-admin';
const availableLanguages = { en: 'English', fr: 'Français', } const LocaleSwitcher = () => { const [locale, setLocale] = useLocaleState(); return ( Language <Button disabled={locale === 'fr'} onClick={() => setLocale('fr')}> English <Button disabled={locale === 'en'} onClick={() => setLocale('en')}> French ); };
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 useNotificationContext
useNotificationContext: () => import('./NotificationContext').NotificationContextType;
function useNotify
useNotify: () => ( message: string | ReactNode, options?: NotificationOptions & { type?: NotificationType }) => void;
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 useOptionalSourceContext
useOptionalSourceContext: () => SourceContextValue | undefined;
function usePaginationState
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);
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 usePickFilterContext
usePickFilterContext: (context: ListControllerResult) => ListFilterContextValue;
function usePickPaginationContext
usePickPaginationContext: ( context: ListControllerResult) => ListPaginationContextValue;
function usePickSaveContext
usePickSaveContext: < ContextType extends SaveContextValue< any, (...args: any[]) => any > = SaveContextValue<any, (...args: any[]) => any>>( context: ContextType) => SaveContextValue;
This hook extracts the
save
,saving
and mutationMode properties from either theCreateContext
orEditContext
. This ensures theSaveContext
doesn't rerender when those two contexts have other properties changes.
function usePickSortContext
usePickSortContext: (context: ListControllerResult) => ListSortContextValue;
function usePreference
usePreference: <T = any>(key?: string, defaultValue?: T) => useStoreResult<T>;
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 usePreferenceKey
usePreferenceKey: () => string | null;
function usePreferencesEditor
usePreferencesEditor: () => PreferencesEditorContextValue;
function usePrevious
usePrevious: (value: any) => undefined;
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) => Partial<RaRecord<import('../types').Identifier>> | null;
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.disableSyncWithStore Controls the selection syncronization with the store
Returns
{Object} Destructure as [selectedIds, { select, toggle, clearSelection }].
function useRedirect
useRedirect: () => ( redirectTo: RedirectionSideEffect, resource?: string, id?: Identifier, data?: Partial<RaRecord>, state?: object) => void;
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) => ...)
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 useReferenceFieldContext
useReferenceFieldContext: () => UseReferenceFieldControllerResult< import('../..').RaRecord<import('../..').Identifier>, Error>;
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) => 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 thechoices
attribute.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
setFilters
function. 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-query
options`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 useReferenceOneFieldController
useReferenceOneFieldController: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>( props: UseReferenceOneFieldControllerParams<RecordType, ErrorType>) => UseReferenceResult<RecordType, ErrorType>;
Fetch a reference record in a one-to-one relationship, and return it when available
The reference prop should be the name of one of the components added as child.
Returns
{UseReferenceResult} The request state. Destructure as { referenceRecord, isPending, error }.
Example 1
const { data, isPending, error } = useReferenceOneFieldController({ record: { id: 7, name: 'James Joyce'} reference: 'bios', target: 'author_id', });
{Object} UseReferenceOneFieldControllerParams {Object} props.record The current resource record {string} props.reference The linked resource name {string} props.target The target resource key {string} props.source The key current record identifier ('id' by default) {Object} props.sort The sort to apply to the referenced records {Object} props.filter The filter to apply to the referenced records
function useRefresh
useRefresh: () => () => void;
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) => (key?: string) => void;
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) => (keyPrefix?: string) => void;
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 useRequireAccess
useRequireAccess: < RecordType extends | RaRecord<Identifier> | Omit<RaRecord<Identifier>, 'id'> = RaRecord<Identifier>, ErrorType extends Error = Error>( params: UseRequireAccessOptions<RecordType, ErrorType>) => | { isError: false; isPending: true; isLoading: true; isLoadingError: false; isRefetchError: false; isSuccess: false; status: 'pending'; dataUpdatedAt: number; errorUpdatedAt: number; failureCount: number; failureReason: ErrorType; errorUpdateCount: number; isFetched: boolean; isFetchedAfterMount: boolean; isFetching: boolean; isInitialLoading: boolean; isPaused: boolean; isPlaceholderData: boolean; isRefetching: boolean; isStale: boolean; refetch: ( options?: | import('@tanstack/query-core/build/legacy/hydration-BZ2M_xzi').ac | undefined ) => Promise<any>; fetchStatus: any; } | { isError: true; isPending: false; isLoading: false; isLoadingError: true; isRefetchError: false; isSuccess: false; status: 'error'; dataUpdatedAt: number; errorUpdatedAt: number; failureCount: number; failureReason: ErrorType; errorUpdateCount: number; isFetched: boolean; isFetchedAfterMount: boolean; isFetching: boolean; isInitialLoading: boolean; isPaused: boolean; isPlaceholderData: boolean; isRefetching: boolean; isStale: boolean; refetch: ( options?: | import('@tanstack/query-core/build/legacy/hydration-BZ2M_xzi').ac | undefined ) => Promise<any>; fetchStatus: any; } | { isError: true; isPending: false; isLoading: false; isLoadingError: false; isRefetchError: true; isSuccess: false; status: 'error'; dataUpdatedAt: number; errorUpdatedAt: number; failureCount: number; failureReason: ErrorType; errorUpdateCount: number; isFetched: boolean; isFetchedAfterMount: boolean; isFetching: boolean; isInitialLoading: boolean; isPaused: boolean; isPlaceholderData: boolean; isRefetching: boolean; isStale: boolean; refetch: ( options?: | import('@tanstack/query-core/build/legacy/hydration-BZ2M_xzi').ac | undefined ) => Promise<any>; fetchStatus: any; } | { isError: false; isPending: false; isLoading: false; isLoadingError: false; isRefetchError: false; isSuccess: true; status: 'success'; dataUpdatedAt: number; errorUpdatedAt: number; failureCount: number; failureReason: ErrorType; errorUpdateCount: number; isFetched: boolean; isFetchedAfterMount: boolean; isFetching: boolean; isInitialLoading: boolean; isPaused: boolean; isPlaceholderData: boolean; isRefetching: boolean; isStale: boolean; refetch: ( options?: | import('@tanstack/query-core/build/legacy/hydration-BZ2M_xzi').ac | undefined ) => Promise<any>; fetchStatus: any; };
A hook that calls the authProvider.canAccess() method for a provided resource and action (and optionally a record). It redirects to the /access-denied page if the user doesn't have the required permissions. It redirects to the /authentication-error page if the authProvider.canAccess throws an error.
The return value updates according to the request state:
- start: { isPending: true } - success: { 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.
Example 1
import { useRequireAccess } from 'react-admin';
const PostDetail = () => { const { isPending } = useRequireAccess({ resource: 'posts', action: 'read', }); if (isPending) { return null; }
return ; };
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: () => () => void;
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: () => import('./ResourceDefinitionContext').ResourceDefinitionContextValue;
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 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
useState
instead, 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 useScrollToTop
useScrollToTop: () => void;
Scroll the window to top when the target location contains the _scrollToTop state
Example 1
// usage in buttons import { Link } from 'react-router-dom'; import { Button } from '@mui/material';
const FooButton = () => ( <Button component={Link} to={{ pathname: '/foo', state: { _scrollToTop: true }, }} > Go to foo );
See Also
CoreAdminRouter where it's enabled by default
function useSelectAll
useSelectAll: (params: UseSelectAllParams) => UseSelectAllResult;
Get a callback to select all records of a resource (capped by the limit parameter)
Parameter params
The hook parameters { resource, sort, filter }
Returns
{Function} handleSelectAll A function to select all items of a list
Example 1
import { List, Datagrid, BulkActionsToolbar, BulkDeleteButton, useListContext, useSelectAll } from 'react-admin';
const MySelectAllButton = () => { const { sort, filter } = useListContext(); const handleSelectAll = useSelectAll({ resource: 'posts', sort, filter }); const handleClick = () => handleSelectAll({ queryOptions: { meta: { foo: 'bar' } }, limit: 250, }); return <button onClick={handleClick}>Select All; };
const PostBulkActionsToolbar = () => ( <BulkActionsToolbar actions={}> );
export const PostList = () => ( <Datagrid bulkActionsToolbar={}> ... );
function useSetInspectorTitle
useSetInspectorTitle: (title: string, options?: any) => void;
Set inspector title on mount
Example 1
useSetInspectorTitle('Datagrid');
function useSetLocale
useSetLocale: () => ( value: string | ((value: string) => void), defaultValue?: string | undefined) => void;
Set the current locale in the I18nContext and re-render the app when the locale changes.
Example 1
import { useSetLocale } from 'react-admin';
const availableLanguages = { en: 'English', fr: 'Français', } const LanguageSwitcher = () => { const setLocale = useSetLocale(); return ( { Object.keys(availableLanguages).map(locale => { <li key={locale} onClick={() => setLocale(locale)}> {availableLanguages[locale]} }) } ); }
function useShowContext
useShowContext: < RecordType extends RaRecord<Identifier> = any, ErrorType = Error>() => ShowControllerResult<RecordType, ErrorType>;
Hook to read the show controller props from the ShowContext.
Used within a (e.g. as a descendent of ).
Returns
{ShowControllerResult} create controller props
See Also
useShowController for how it is filled
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 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 useSourceContext
useSourceContext: () => SourceContextValue;
function useSplatPathBase
useSplatPathBase: () => string;
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 = any>(key: string, defaultValue?: T) => useStoreResult<T>;
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: () => import('./types').Store;
Get the Store stored in the StoreContext
function useSuggestions
useSuggestions: ({ allowCreate, choices, createText, createValue, limitChoicesToValue, matchSuggestion, optionText, optionValue, selectedItem, suggestionLimit, translateChoice,}: UseSuggestionsOptions) => { getChoiceText: (choice: any) => string | import('react').JSX.Element; getChoiceValue: (choice: any) => any; getSuggestions: (filter: any) => any[];};
function useTakeUndoableMutation
useTakeUndoableMutation: () => () => void | import('./types').UndoableMutation;
function useTimeout
useTimeout: (ms?: number, key?: string) => boolean;
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) => any[];
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: () => ({ source, label, resource,}: { source?: string | undefined; label?: ReactNode; resource?: string | undefined;}) => | string | number | true | import('react').ReactElement< any, string | import('react').JSXElementConstructor<any> > | Iterable<ReactNode> | null;
function useUnique
useUnique: ( options?: UseUniqueOptions) => ( callTimeOptions?: UseUniqueOptions) => ( value: any, allValues: any, props: InputProps) => Promise< | string | { message: any; args: { source: string; value: any; field: | string | number | true | import('react').ReactElement< any, string | import('react').JSXElementConstructor<any> > | Iterable<import('react').ReactNode> | null; }; }>;
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) => (ids: Identifier[]) => void;
Hook to Unselect the rows of a datagrid
Example 1
const unselect = useUnselect('posts'); unselect([123, 456]);
function useUnselectAll
useUnselectAll: (resource?: string) => () => void;
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?: any) => 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?: any) => 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 useWarnWhenUnsavedChanges
useWarnWhenUnsavedChanges: ( enable: boolean, formRootPathname?: string, control?: Control) => void;
Display a confirmation dialog if the form has unsaved changes. - If the user confirms, the navigation continues and the changes are lost. - If the user cancels, the navigation is cancelled and the changes are kept.
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) => string;
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 ValidationError
ValidationError: (props: ValidationErrorProps) => React.JSX.Element;
function warning
warning: (condition: any, message: string) => void;
function WarnWhenUnsavedChanges
WarnWhenUnsavedChanges: ({ enable, formRootPathName, formControl,}: { enable?: boolean | undefined; formRootPathName: any; formControl: any;}) => null;
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; }, }, ] );
function WithListContext
WithListContext: <RecordType extends RaRecord<Identifier>>({ render,}: WithListContextProps<RecordType>) => ReactElement< any, string | import('react').JSXElementConstructor<any>> | null;
Render prop version of useListContext
Example 1
const BookList = () => ( <WithListContext render={({ data }) => ( {data && data.map(record => ( <li key={record.id}>{record.title} ))} )} /> );
function WithRecord
WithRecord: <RecordType extends Record<string, any> = any>({ render,}: WithRecordProps<RecordType>) => React.JSX.Element | null;
Render prop version of useRecordContext
Example 1
const BookShow = () => ( <WithRecord render={record => {record.title}} /> );
Classes
class HttpError
class HttpError extends Error {}
constructor
constructor(message: any, status: any, body?: any);
property body
readonly body: any;
property message
readonly message: any;
property status
readonly status: any;
class InferredElement
class InferredElement {}
constructor
constructor(type?: InferredType, props?: any, children?: any);
method getElement
getElement: (props?: {}) => | import('react').ReactElement< {}, string | import('react').JSXElementConstructor<any> > | undefined;
method getProps
getProps: () => any;
method getRepresentation
getRepresentation: () => string;
method isDefined
isDefined: () => boolean;
Interfaces
interface AdminRouterProps
interface AdminRouterProps {}
interface AuthenticatedProps
interface AuthenticatedProps {}
property authParams
authParams?: object;
property children
children: ReactNode;
property loading
loading?: ReactNode;
property requireAuth
requireAuth?: boolean;
Deprecated
Authenticated now never renders children when not authenticated.
interface CanAccessProps
interface CanAccessProps< RecordType extends RaRecord | Omit<RaRecord, 'id'> = RaRecord, ErrorType extends Error = Error> extends UseCanAccessOptions<RecordType, ErrorType> {}
property accessDenied
accessDenied?: React.ReactNode;
property children
children: React.ReactNode;
property error
error?: React.ReactNode;
property loading
loading?: React.ReactNode;
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 ChoicesProps
interface ChoicesProps {}
property choices
choices?: any[];
property isFetching
isFetching?: boolean;
property isLoading
isLoading?: boolean;
property isPending
isPending?: boolean;
property optionText
optionText?: OptionText;
property optionValue
optionValue?: string;
property translateChoice
translateChoice?: boolean;
interface CoreAdminContextProps
interface CoreAdminContextProps {}
property authProvider
authProvider?: AuthProvider | LegacyAuthProvider;
The authentication provider for security and permissions
Example 1
import authProvider from './authProvider';
const App = () => ( <Admin authProvider={authProvider}> ... );
See Also
https://marmelab.com/react-admin/Authentication.html
property basename
basename?: string;
The base path for all URLs generated by react-admin.
Example 1
import { Admin } from 'react-admin'; import { BrowserRouter } from 'react-router-dom'; import { dataProvider } from './dataProvider';
const App = () => ( <Admin basename="/admin" dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#using-react-admin-in-a-sub-path
property children
children?: AdminChildren;
property dashboard
dashboard?: DashboardComponent;
The component to use for the dashboard page (displayed on the
/
route).Example 1
import { Admin } from 'react-admin'; import Dashboard from './Dashboard'; import { dataProvider } from './dataProvider';
const App = () => ( <Admin dashboard={Dashboard} dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#dashboard
property dataProvider
dataProvider?: DataProvider | LegacyDataProvider;
The data provider used to communicate with the API
Example 1
import { Admin } from 'react-admin'; import simpleRestProvider from 'ra-data-simple-rest'; const dataProvider = simpleRestProvider('http://path.to.my.api/');
const App = () => ( <Admin dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/DataProviders.html
property i18nProvider
i18nProvider?: I18nProvider;
The internationalization provider for translations
Example 1
// in src/i18nProvider.js import polyglotI18nProvider from 'ra-i18n-polyglot'; import fr from 'ra-language-french';
export const i18nProvider = polyglotI18nProvider(() => fr, 'fr');
// in src/App.js import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider'; import { i18nProvider } from './i18nProvider';
const App = () => ( <Admin dataProvider={dataProvider} i18nProvider={i18nProvider}> ... );
See Also
https://marmelab.com/react-admin/Translation.html
property queryClient
queryClient?: QueryClient;
The react-query client
Example 1
import { Admin } from 'react-admin'; import { QueryClient } from '@tanstack/react-query';
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, structuralSharing: false, }, mutations: { retryDelay: 10000, }, }, });
const App = () => ( <Admin queryClient={queryClient} dataProvider={...}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#queryclient
property store
store?: Store;
The adapter for storing user preferences
Example 1
import { Admin, memoryStore } from 'react-admin';
const App = () => ( <Admin dataProvider={dataProvider} store={memoryStore()}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#store
interface CoreAdminRoutesProps
interface CoreAdminRoutesProps {}
property accessDenied
accessDenied?: React.ComponentType;
property authenticationError
authenticationError?: ComponentType;
property catchAll
catchAll: CatchAllComponent;
property children
children?: AdminChildren;
property dashboard
dashboard?: DashboardComponent;
property layout
layout: LayoutComponent;
property loading
loading: LoadingComponent;
property ready
ready?: ComponentType;
property requireAuth
requireAuth?: boolean;
interface CoreAdminUIProps
interface CoreAdminUIProps {}
property accessDenied
accessDenied?: React.ComponentType;
A react component to display when users don't have access to the page they're trying to access
Example 1
// in src/AccessDenied.js import Card from '@mui/material/Card'; import CardContent from '@mui/material/CardContent'; import { Title } from 'react-admin';
export const AccessDenied = () => ( You're not authorized to see this page );
// in src/App.js import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider'; import { AccessDenied } from './AccessDenied';
const App = () => ( <Admin accessDenied={AccessDenied} dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#accessDenied
property authCallbackPage
authCallbackPage?: ComponentType | boolean;
The content displayed when the user visits the /auth-callback page, used for redirection by third-party authentication providers
Example 1
import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider'; import { authProvider } from './authProvider'; import MyAuthCallbackPage from './MyAuthCallbackPage';
const App = () => ( <Admin authCallbackPage={MyAuthCallbackPage} authProvider={authProvider} dataProvider={dataProvider} > ... );
See Also
https://marmelab.com/react-admin/Admin.html#authcallbackpage
property authenticationError
authenticationError?: ComponentType;
The page to display when an authentication error occurs
Example 1
import { Admin } from 'react-admin';
const AuthenticationError = () => ( Authentication Error The authentication server returned an error and your credentials could not be checked. )
const App = () => ( <Admin authenticationError={AuthenticationError}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#authenticationError
property catchAll
catchAll?: CatchAllComponent;
A catch-all react component to display when the URL does not match any
Example 1
// in src/NotFound.js import Card from '@mui/material/Card'; import CardContent from '@mui/material/CardContent'; import { Title } from 'react-admin';
export const NotFound = () => ( 404: Page not found );
// in src/App.js import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider'; import { NotFound } from './NotFound';
const App = () => ( <Admin catchAll={NotFound} dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#catchall
property children
children?: AdminChildren;
property dashboard
dashboard?: DashboardComponent;
The component to use for the dashboard page (displayed on the
/
route).Example 1
import { Admin } from 'react-admin'; import Dashboard from './Dashboard'; import { dataProvider } from './dataProvider';
const App = () => ( <Admin dashboard={Dashboard} dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#dashboard
property disableTelemetry
disableTelemetry?: boolean;
Set to true to disable anonymous telemetry collection
Example 1
import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider';
const App = () => ( <Admin disableTelemetry dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#disabletelemetry
property error
error?: ({ errorInfo, error, resetErrorBoundary,}: { errorInfo?: ErrorInfo; error: Error; resetErrorBoundary: (args: any) => void;}) => ReactElement;
The component displayed when an error is caught in a child component
Example 1
import { Admin } from 'react-admin'; import { MyError } from './error';
const App = () => ( <Admin error={MyError}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#error
property layout
layout?: LayoutComponent;
The main app layout component
Example 1
import { Admin, Layout } from 'react-admin';
const MyLayout = ({ children }) => ( <Layout appBarAlwaysOn> {children} );
export const App = () => ( <Admin dataProvider={dataProvider} layout={MyLayout}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#layout
property loading
loading?: LoadingComponent;
The component displayed while fetching the auth provider if the admin child is an async function
property loginPage
loginPage?: LoginComponent | boolean;
The component displayed when the user visits the /login page
Example 1
import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider'; import { authProvider } from './authProvider'; import MyLoginPage from './MyLoginPage';
const App = () => ( <Admin loginPage={MyLoginPage} authProvider={authProvider} dataProvider={dataProvider} > ... );
See Also
https://marmelab.com/react-admin/Admin.html#loginpage
property ready
ready?: ComponentType;
The page to display when the admin has no Resource children
Example 1
import { Admin } from 'react-admin';
const Ready = () => ( Admin ready You can now add resources )
const App = () => ( <Admin ready={Ready}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#ready
property requireAuth
requireAuth?: boolean;
Flag to require authentication for all routes. Defaults to false.
Example 1
import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider'; import { authProvider } from './authProvider';
const App = () => ( <Admin requireAuth authProvider={authProvider} dataProvider={dataProvider} > ... );
See Also
https://marmelab.com/react-admin/Admin.html#requireauth
property title
title?: TitleComponent;
The title of the error page
Example 1
import { Admin } from 'react-admin'; import { dataProvider } from './dataProvider';
const App = () => ( <Admin title="My Admin" dataProvider={dataProvider}> ... );
See Also
https://marmelab.com/react-admin/Admin.html#title
interface CoreLayoutProps
interface CoreLayoutProps {}
property children
children: ReactNode;
interface CreateBaseProps
interface CreateBaseProps< RecordType extends Omit<RaRecord, 'id'> = any, ResultRecordType extends RaRecord = RecordType & { id: Identifier; }, MutationOptionsError = Error> extends CreateControllerProps< RecordType, MutationOptionsError, ResultRecordType > {}
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 EditBaseProps
interface EditBaseProps<RecordType extends RaRecord = RaRecord, ErrorType = Error> extends EditControllerProps<RecordType, ErrorType> {}
interface EditControllerBaseResult
interface EditControllerBaseResult<RecordType extends RaRecord = any> extends SaveContextValue<RecordType> {}
property defaultTitle
defaultTitle?: string;
property isFetching
isFetching: boolean;
property isLoading
isLoading: boolean;
property redirect
redirect: 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 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 FieldTitleProps
interface FieldTitleProps {}
property isRequired
isRequired?: boolean;
property label
label?: React.ReactNode;
property resource
resource?: string;
property source
source?: string;
interface FilterLiveFormProps
interface FilterLiveFormProps extends Omit<UseFormProps, 'onSubmit' | 'defaultValues'> {}
property children
children: ReactNode;
property debounce
debounce?: number | false;
property formComponent
formComponent?: React.ComponentType< Pick<React.HTMLAttributes<HTMLFormElement>, 'onSubmit'>>;
property resource
resource?: string;
property validate
validate?: ValidateForm;
interface FilterPayload
interface FilterPayload {}
index signature
[k: string]: any;
interface FormDataConsumerRenderParams
interface FormDataConsumerRenderParams< TFieldValues extends FieldValues = FieldValues, TScopedFieldValues extends FieldValues = TFieldValues> {}
property formData
formData: TFieldValues;
property scopedFormData
scopedFormData?: TScopedFieldValues;
interface FormOwnProps
interface FormOwnProps<RecordType = any> {}
property children
children: ReactNode;
property className
className?: string;
property defaultValues
defaultValues?: any;
property disableInvalidFormNotification
disableInvalidFormNotification?: boolean;
property formRootPathname
formRootPathname?: string;
property id
id?: string;
property onSubmit
onSubmit?: SubmitHandler<FieldValues> | SaveHandler<RecordType>;
property record
record?: Partial<RaRecord>;
property resource
resource?: string;
property sanitizeEmptyValues
sanitizeEmptyValues?: boolean;
property warnWhenUnsavedChanges
warnWhenUnsavedChanges?: boolean;
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 HandleSelectAllParams
interface HandleSelectAllParams<RecordType extends RaRecord = any> {}
property limit
limit?: number;
property queryOptions
queryOptions?: UseGetListOptions<RecordType>;
interface I18nContextProviderProps
interface I18nContextProviderProps {}
interface IMessages
interface IMessages extends Record<string, string | ((options?: any) => string) | IMessages> {}
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 InfiniteListBaseProps
interface InfiniteListBaseProps<RecordType extends RaRecord = any> extends InfiniteListControllerProps<RecordType> {}
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 ListBaseProps
interface ListBaseProps<RecordType extends RaRecord = any> extends ListControllerProps<RecordType> {}
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 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: () => 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 RecordContextProviderProps
interface RecordContextProviderProps<RecordType> {}
interface ReferenceFieldBaseProps
interface ReferenceFieldBaseProps<ReferenceRecordType extends RaRecord = RaRecord> {}
interface ReferenceInputBaseProps
interface ReferenceInputBaseProps extends InputProps, UseReferenceInputControllerParams {}
property children
children?: ReactNode;
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?: ReactElement | RecordToStringFunction | string;
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?: ReactElement | RecordToStringFunction | string;
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 ShowBaseProps
interface ShowBaseProps<RecordType extends RaRecord = RaRecord> extends ShowControllerProps<RecordType> {}
interface ShowControllerBaseResult
interface ShowControllerBaseResult<RecordType extends RaRecord = any> {}
property defaultTitle
defaultTitle?: string;
property isFetching
isFetching: boolean;
property isLoading
isLoading: boolean;
property record
record?: RecordType;
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 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;
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 StoreContextProviderProps
interface StoreContextProviderProps {}
interface StoreSetterProps
interface StoreSetterProps {}
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 TranslateProps
interface TranslateProps {}
interface TranslationMessages
interface TranslationMessages extends StringMap {}
property ra
ra: { action: { [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; save: string; search: 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; }; 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 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 UseChoicesOptions
interface UseChoicesOptions {}
property disableValue
disableValue?: string;
property optionText
optionText?: OptionText;
property optionValue
optionValue?: string;
property translateChoice
translateChoice?: boolean;
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 isPending
isPending?: 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<{ data: RecordType[]; total?: number; pageInfo?: { hasNextPage?: boolean; hasPreviousPage?: boolean; }; }>, '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 UseReferenceOneFieldControllerParams
interface UseReferenceOneFieldControllerParams< RecordType extends RaRecord = any, ErrorType = Error> {}
property filter
filter?: any;
property queryOptions
queryOptions?: Omit< UseQueryOptions< { data: RecordType[]; total: number; }, ErrorType >, 'queryFn' | 'queryKey'> & { meta?: any;};
property record
record?: RaRecord;
property reference
reference: string;
property sort
sort?: SortPayload;
property source
source?: 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 isPending
isPending: 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?: | string | React.ReactElement | ((record: any) => string);
property resource
readonly resource?: string;
interface UserIdentity
interface UserIdentity {}
property avatar
avatar?: string;
property fullName
fullName?: string;
property id
id: Identifier;
index signature
[key: string]: any;
interface UseSelectAllParams
interface UseSelectAllParams {}
interface UseSuggestionsOptions
interface UseSuggestionsOptions extends UseChoicesOptions {}
property allowCreate
allowCreate?: boolean;
property allowDuplicates
allowDuplicates?: boolean;
property choices
choices?: any[];
property createText
createText?: string;
property createValue
createValue?: any;
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 {}
interface ValidationErrorProps
interface ValidationErrorProps {}
property error
error: ValidationErrorMessage;
interface WithListContextProps
interface WithListContextProps<RecordType extends RaRecord> {}
interface WithPermissionsProps
interface WithPermissionsProps {}
property authParams
authParams?: object;
property children
children?: WithPermissionsChildren;
property component
component?: ComponentType<any>;
property loading
loading?: ComponentType<any>;
property location
location?: Location;
property render
render?: WithPermissionsChildren;
property staticContext
staticContext?: object;
index signature
[key: string]: any;
interface WithRecordProps
interface WithRecordProps<RecordType extends Record<string, any> = any> {}
Type Aliases
type AdminChildren
type AdminChildren = | RenderResourcesFunction | Iterable<ReactNode | RenderResourcesFunction> | ReactNode;
type AnyString
type AnyString = string & {};
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 ChildrenFunction
type ChildrenFunction = () => ComponentType[];
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; 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 CoreAdminProps
type CoreAdminProps = CoreAdminContextProps & CoreAdminUIProps;
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 CustomRoutesProps
type CustomRoutesProps = { children: ReactNode; noLayout?: boolean;};
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 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> = [T] extends [never] ? string : RecordPath<T>;
type FetchRelatedRecords
type FetchRelatedRecords = <RecordType = any>( data: any[], field: string, resource: string) => Promise<{ [key: Identifier]: RecordType;}>;
type FormDataConsumerRender
type FormDataConsumerRender<TFieldValues extends FieldValues = FieldValues> = ( params: FormDataConsumerRenderParams<TFieldValues>) => ReactNode;
type FormFunctions
type FormFunctions = { setOnSave?: SetOnSave;};
type FormGroupContextValue
type FormGroupContextValue = string;
type FormProps
type FormProps<RecordType = any> = FormOwnProps<RecordType> & Omit<UseFormProps, 'onSubmit'> & { validate?: ValidateForm; noValidate?: boolean; WarnWhenUnsavedChangesComponent?: React.ComponentType<{ enable?: boolean; formRootPathName?: string; formControl?: any; }>; };
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 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?: string | ReactElement | false; helperText?: string | ReactElement | false; 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 ListFilterContextValue
type ListFilterContextValue = Pick< ListControllerResult, | 'displayedFilters' | 'filterValues' | 'hideFilter' | 'setFilters' | 'showFilter' | 'resource'>;
type ListPaginationContextValue
type ListPaginationContextValue = Pick< ListControllerResult, | 'isLoading' | 'isPending' | 'hasPreviousPage' | 'hasNextPage' | 'page' | 'perPage' | 'setPage' | 'setPerPage' | 'total' | 'resource'>;
type ListSortContextValue
type ListSortContextValue = Pick< ListControllerResult, 'sort' | 'setSort' | 'resource'>;
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 MutationMode
type MutationMode = 'pessimistic' | 'optimistic' | 'undoable';
type NavigateToFirstResourceProps
type NavigateToFirstResourceProps = { loading: React.ComponentType;};
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, context?: any) => void;
type OnSuccess
type OnSuccess = (response?: any, variables?: any, context?: any) => void;
type OptionText
type OptionText = OptionTextElement | OptionTextFunc | string;
type OptionTextElement
type OptionTextElement = ReactElement<{ record: RaRecord;}>;
type OptionTextFunc
type OptionTextFunc = (choice: any) => React.ReactNode;
type PossibleInferredElementTypes
type PossibleInferredElementTypes = (typeof InferenceTypes)[number];
type PreferencesEditorContextValue
type PreferencesEditorContextValue = { editor: ReactElement | null; setEditor: React.Dispatch<React.SetStateAction<ReactElement | null>>; preferenceKey: string | null; setPreferenceKey: React.Dispatch<React.SetStateAction<string | null>>; title: string | null; titleOptions?: any; setTitle: (title: string, titleOptions?: any) => void; isEnabled: boolean; enable: () => void; disable: () => void; path: string | null; setPath: (path: string) => void;};
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 RenderResourcesFunction
type RenderResourcesFunction = ( permissions: any) => ReactNode | Promise<ReactNode> | ResourceElement[] | 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>>; /** * 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 ResourceDefinitionContextValue
type ResourceDefinitionContextValue = { definitions: ResourceDefinitions; register: (config: ResourceDefinition) => void; unregister: (config: ResourceDefinition) => void;};
type ResourceDefinitions
type ResourceDefinitions<OptionsType extends ResourceOptions = any> = { [name: string]: ResourceDefinition<OptionsType>;};
type ResourceElement
type ResourceElement = ReactElement<ResourceProps>;
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 SourceContextValue
type SourceContextValue = { getSource: (source: string) => string; getLabel: (source: string) => string;};
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 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> = UseMutationOptions< RecordType['id'][], MutationError, Partial<UseDeleteManyMutateParams<RecordType>>> & { mutationMode?: MutationMode;};
type UseDeleteManyResult
type UseDeleteManyResult< RecordType extends RaRecord = any, MutationError = unknown> = [ ( resource?: string, params?: Partial<DeleteManyParams<RecordType>>, options?: MutateOptions< RecordType['id'][], MutationError, Partial<UseDeleteManyMutateParams<RecordType>>, unknown > & { mutationMode?: MutationMode; } ) => Promise<void>, UseMutationResult< RecordType['id'][], MutationError, Partial< DeleteManyParams<RecordType> & { resource?: string; } >, unknown > & { isLoading: boolean; }];
type UseDeleteOptions
type UseDeleteOptions< RecordType extends RaRecord = any, MutationError = unknown> = UseMutationOptions< RecordType, MutationError, Partial<UseDeleteMutateParams<RecordType>>> & { mutationMode?: MutationMode; onSuccess?: ( data: RecordType | undefined, variables: Partial<UseDeleteMutateParams<RecordType>>, context: unknown ) => void;};
type UseDeleteResult
type UseDeleteResult<RecordType extends RaRecord = any, MutationError = unknown> = [ ( resource?: string, params?: Partial<DeleteParams<RecordType>>, options?: MutateOptions< RecordType, MutationError, Partial<UseDeleteMutateParams<RecordType>>, unknown > & { mutationMode?: MutationMode; } ) => Promise<void>, UseMutationResult< RecordType, 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, 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;};
type UseInfiniteGetListOptions
type UseInfiniteGetListOptions< RecordType extends RaRecord = any, ErrorType = Error> = Omit< UseInfiniteQueryOptions< GetInfiniteListResult<RecordType>, ErrorType, InfiniteData<GetInfiniteListResult<RecordType>>, 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 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'][]) => void; toggle: (id: RecordType['id']) => void; clearSelection: () => void; }];
type UseRequireAccessOptions
type UseRequireAccessOptions< RecordType extends RaRecord | Omit<RaRecord, 'id'> = RaRecord, ErrorType extends Error = Error> = UseCanAccessOptions<RecordType, ErrorType>;
type UseRequireAccessResult
type UseRequireAccessResult<ErrorType extends Error = Error> = Omit< UseCanAccessResult<ErrorType>, 'canAccess' | 'data'>;
type UseSelectAllResult
type UseSelectAllResult = (options?: HandleSelectAllParams) => 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> = UseMutationOptions< Array<RecordType['id']>, MutationError, Partial<Omit<UseUpdateManyMutateParams<RecordType>, 'mutationFn'>>> & { mutationMode?: MutationMode; returnPromise?: boolean;};
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']>, MutationError, Partial< UpdateManyParams<Partial<RecordType>> & { resource?: string; } >, unknown > & { isLoading: boolean; }];
type UseUpdateOptions
type UseUpdateOptions< RecordType extends RaRecord = any, ErrorType = Error> = UseMutationOptions< RecordType, ErrorType, Partial<Omit<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 'dist/cjs/dataProvider/fetch.d.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;
Package Files (267)
- dist/cjs/auth/AuthContext.d.ts
- dist/cjs/auth/Authenticated.d.ts
- dist/cjs/auth/CanAccess.d.ts
- dist/cjs/auth/LogoutOnMount.d.ts
- dist/cjs/auth/WithPermissions.d.ts
- dist/cjs/auth/addRefreshAuthToAuthProvider.d.ts
- dist/cjs/auth/addRefreshAuthToDataProvider.d.ts
- dist/cjs/auth/convertLegacyAuthProvider.d.ts
- dist/cjs/auth/types.d.ts
- dist/cjs/auth/useAuthProvider.d.ts
- dist/cjs/auth/useAuthState.d.ts
- dist/cjs/auth/useAuthenticated.d.ts
- dist/cjs/auth/useCanAccess.d.ts
- dist/cjs/auth/useCanAccessCallback.d.ts
- dist/cjs/auth/useCanAccessResources.d.ts
- dist/cjs/auth/useCheckAuth.d.ts
- dist/cjs/auth/useGetIdentity.d.ts
- dist/cjs/auth/useGetPermissions.d.ts
- dist/cjs/auth/useHandleAuthCallback.d.ts
- dist/cjs/auth/useIsAuthPending.d.ts
- dist/cjs/auth/useLogin.d.ts
- dist/cjs/auth/useLogout.d.ts
- dist/cjs/auth/useLogoutIfAccessDenied.d.ts
- dist/cjs/auth/usePermissions.d.ts
- dist/cjs/auth/useRequireAccess.d.ts
- dist/cjs/controller/button/useDeleteWithConfirmController.d.ts
- dist/cjs/controller/button/useDeleteWithUndoController.d.ts
- dist/cjs/controller/checkMinimumRequiredProps.d.ts
- dist/cjs/controller/create/CreateBase.d.ts
- dist/cjs/controller/create/CreateContext.d.ts
- dist/cjs/controller/create/CreateContextProvider.d.ts
- dist/cjs/controller/create/CreateController.d.ts
- dist/cjs/controller/create/useCreateContext.d.ts
- dist/cjs/controller/create/useCreateController.d.ts
- dist/cjs/controller/edit/EditBase.d.ts
- dist/cjs/controller/edit/EditContext.d.ts
- dist/cjs/controller/edit/EditContextProvider.d.ts
- dist/cjs/controller/edit/EditController.d.ts
- dist/cjs/controller/edit/useEditContext.d.ts
- dist/cjs/controller/edit/useEditController.d.ts
- dist/cjs/controller/field/ReferenceFieldBase.d.ts
- dist/cjs/controller/field/ReferenceFieldContext.d.ts
- dist/cjs/controller/field/useReferenceArrayFieldController.d.ts
- dist/cjs/controller/field/useReferenceFieldController.d.ts
- dist/cjs/controller/field/useReferenceManyFieldController.d.ts
- dist/cjs/controller/field/useReferenceOneFieldController.d.ts
- dist/cjs/controller/input/ReferenceInputBase.d.ts
- dist/cjs/controller/input/referenceDataStatus.d.ts
- dist/cjs/controller/input/useReferenceArrayInputController.d.ts
- dist/cjs/controller/input/useReferenceInputController.d.ts
- dist/cjs/controller/list/InfiniteListBase.d.ts
- dist/cjs/controller/list/InfinitePaginationContext.d.ts
- dist/cjs/controller/list/ListBase.d.ts
- dist/cjs/controller/list/ListContext.d.ts
- dist/cjs/controller/list/ListContextProvider.d.ts
- dist/cjs/controller/list/ListController.d.ts
- dist/cjs/controller/list/ListFilterContext.d.ts
- dist/cjs/controller/list/ListPaginationContext.d.ts
- dist/cjs/controller/list/ListSortContext.d.ts
- dist/cjs/controller/list/WithListContext.d.ts
- dist/cjs/controller/list/queryReducer.d.ts
- dist/cjs/controller/list/useExpanded.d.ts
- dist/cjs/controller/list/useInfiniteListController.d.ts
- dist/cjs/controller/list/useInfinitePaginationContext.d.ts
- dist/cjs/controller/list/useList.d.ts
- dist/cjs/controller/list/useListContext.d.ts
- dist/cjs/controller/list/useListContextWithProps.d.ts
- dist/cjs/controller/list/useListController.d.ts
- dist/cjs/controller/list/useListFilterContext.d.ts
- dist/cjs/controller/list/useListPaginationContext.d.ts
- dist/cjs/controller/list/useListParams.d.ts
- dist/cjs/controller/list/useListSortContext.d.ts
- dist/cjs/controller/list/useRecordSelection.d.ts
- dist/cjs/controller/list/useSelectAll.d.ts
- dist/cjs/controller/list/useUnselect.d.ts
- dist/cjs/controller/list/useUnselectAll.d.ts
- dist/cjs/controller/record/OptionalRecordContextProvider.d.ts
- dist/cjs/controller/record/RecordContext.d.ts
- dist/cjs/controller/record/RecordRepresentation.d.ts
- dist/cjs/controller/record/WithRecord.d.ts
- dist/cjs/controller/record/useRecordContext.d.ts
- dist/cjs/controller/saveContext/SaveContext.d.ts
- dist/cjs/controller/saveContext/SaveContextProvider.d.ts
- dist/cjs/controller/saveContext/useMutationMiddlewares.d.ts
- dist/cjs/controller/saveContext/usePickSaveContext.d.ts
- dist/cjs/controller/saveContext/useRegisterMutationMiddleware.d.ts
- dist/cjs/controller/saveContext/useSaveContext.d.ts
- dist/cjs/controller/show/ShowBase.d.ts
- dist/cjs/controller/show/ShowContext.d.ts
- dist/cjs/controller/show/ShowContextProvider.d.ts
- dist/cjs/controller/show/ShowController.d.ts
- dist/cjs/controller/show/useShowContext.d.ts
- dist/cjs/controller/show/useShowController.d.ts
- dist/cjs/controller/useFilterState.d.ts
- dist/cjs/controller/usePaginationState.d.ts
- dist/cjs/controller/usePrevNextController.d.ts
- dist/cjs/controller/useReference.d.ts
- dist/cjs/controller/useSortState.d.ts
- dist/cjs/core/CoreAdmin.d.ts
- dist/cjs/core/CoreAdminContext.d.ts
- dist/cjs/core/CoreAdminRoutes.d.ts
- dist/cjs/core/CoreAdminUI.d.ts
- dist/cjs/core/CustomRoutes.d.ts
- dist/cjs/core/DefaultTitleContext.d.ts
- dist/cjs/core/HasDashboardContext.d.ts
- dist/cjs/core/NavigateToFirstResource.d.ts
- dist/cjs/core/OptionalResourceContextProvider.d.ts
- dist/cjs/core/Resource.d.ts
- dist/cjs/core/ResourceContext.d.ts
- dist/cjs/core/ResourceContextProvider.d.ts
- dist/cjs/core/ResourceDefinitionContext.d.ts
- dist/cjs/core/SourceContext.d.ts
- dist/cjs/core/useFirstResourceWithListAccess.d.ts
- dist/cjs/core/useGetRecordRepresentation.d.ts
- dist/cjs/core/useGetResourceLabel.d.ts
- dist/cjs/core/useResourceContext.d.ts
- dist/cjs/core/useResourceDefinition.d.ts
- dist/cjs/core/useResourceDefinitionContext.d.ts
- dist/cjs/core/useResourceDefinitions.d.ts
- dist/cjs/core/useWrappedSource.d.ts
- dist/cjs/dataProvider/DataProviderContext.d.ts
- dist/cjs/dataProvider/HttpError.d.ts
- dist/cjs/dataProvider/combineDataProviders.d.ts
- dist/cjs/dataProvider/convertLegacyDataProvider.d.ts
- dist/cjs/dataProvider/dataFetchActions.d.ts
- dist/cjs/dataProvider/defaultDataProvider.d.ts
- dist/cjs/dataProvider/fetch.d.ts
- dist/cjs/dataProvider/testDataProvider.d.ts
- dist/cjs/dataProvider/undo/AddUndoableMutationContext.d.ts
- dist/cjs/dataProvider/undo/TakeUndoableMutationContext.d.ts
- dist/cjs/dataProvider/undo/UndoableMutationsContextProvider.d.ts
- dist/cjs/dataProvider/undo/types.d.ts
- dist/cjs/dataProvider/undo/useAddUndoableMutation.d.ts
- dist/cjs/dataProvider/undo/useTakeUndoableMutation.d.ts
- dist/cjs/dataProvider/undoableEventEmitter.d.ts
- dist/cjs/dataProvider/useCreate.d.ts
- dist/cjs/dataProvider/useDataProvider.d.ts
- dist/cjs/dataProvider/useDelete.d.ts
- dist/cjs/dataProvider/useDeleteMany.d.ts
- dist/cjs/dataProvider/useGetList.d.ts
- dist/cjs/dataProvider/useGetMany.d.ts
- dist/cjs/dataProvider/useGetManyAggregate.d.ts
- dist/cjs/dataProvider/useGetManyReference.d.ts
- dist/cjs/dataProvider/useGetOne.d.ts
- dist/cjs/dataProvider/useGetRecordId.d.ts
- dist/cjs/dataProvider/useInfiniteGetList.d.ts
- dist/cjs/dataProvider/useIsDataLoaded.d.ts
- dist/cjs/dataProvider/useLoading.d.ts
- dist/cjs/dataProvider/useRefresh.d.ts
- dist/cjs/dataProvider/useUpdate.d.ts
- dist/cjs/dataProvider/useUpdateMany.d.ts
- dist/cjs/dataProvider/withLifecycleCallbacks.d.ts
- dist/cjs/export/ExporterContext.d.ts
- dist/cjs/export/defaultExporter.d.ts
- dist/cjs/export/downloadCSV.d.ts
- dist/cjs/export/fetchRelatedRecords.d.ts
- dist/cjs/form/FilterLiveForm.d.ts
- dist/cjs/form/Form.d.ts
- dist/cjs/form/FormDataConsumer.d.ts
- dist/cjs/form/WarnWhenUnsavedChanges.d.ts
- dist/cjs/form/choices/ChoicesContext.d.ts
- dist/cjs/form/choices/ChoicesContextProvider.d.ts
- dist/cjs/form/choices/useChoices.d.ts
- dist/cjs/form/choices/useChoicesContext.d.ts
- dist/cjs/form/groups/FormGroupContext.d.ts
- dist/cjs/form/groups/FormGroupContextProvider.d.ts
- dist/cjs/form/groups/FormGroupsProvider.d.ts
- dist/cjs/form/groups/useFormGroup.d.ts
- dist/cjs/form/groups/useFormGroupContext.d.ts
- dist/cjs/form/groups/useFormGroups.d.ts
- dist/cjs/form/useApplyInputDefaultValues.d.ts
- dist/cjs/form/useAugmentedForm.d.ts
- dist/cjs/form/useInput.d.ts
- dist/cjs/form/useRecordFromLocation.d.ts
- dist/cjs/form/useSuggestions.d.ts
- dist/cjs/form/useWarnWhenUnsavedChanges.d.ts
- dist/cjs/form/validation/ValidationError.d.ts
- dist/cjs/form/validation/getSimpleValidationResolver.d.ts
- dist/cjs/form/validation/setSubmissionErrors.d.ts
- dist/cjs/form/validation/useGetValidationErrorMessage.d.ts
- dist/cjs/form/validation/useNotifyIsFormInvalid.d.ts
- dist/cjs/form/validation/useUnique.d.ts
- dist/cjs/form/validation/validate.d.ts
- dist/cjs/i18n/I18nContext.d.ts
- dist/cjs/i18n/I18nContextProvider.d.ts
- dist/cjs/i18n/TestTranslationProvider.d.ts
- dist/cjs/i18n/TranslatableContext.d.ts
- dist/cjs/i18n/TranslatableContextProvider.d.ts
- dist/cjs/i18n/Translate.d.ts
- dist/cjs/i18n/TranslationMessages.d.ts
- dist/cjs/i18n/TranslationUtils.d.ts
- dist/cjs/i18n/index.d.ts
- dist/cjs/i18n/substituteTokens.d.ts
- dist/cjs/i18n/useI18nProvider.d.ts
- dist/cjs/i18n/useLocale.d.ts
- dist/cjs/i18n/useLocaleState.d.ts
- dist/cjs/i18n/useLocales.d.ts
- dist/cjs/i18n/useSetLocale.d.ts
- dist/cjs/i18n/useTranslatable.d.ts
- dist/cjs/i18n/useTranslatableContext.d.ts
- dist/cjs/i18n/useTranslate.d.ts
- dist/cjs/i18n/useTranslateLabel.d.ts
- dist/cjs/index.d.ts
- dist/cjs/inference/InferredElement.d.ts
- dist/cjs/inference/getElementsFromRecords.d.ts
- dist/cjs/inference/getValuesFromRecords.d.ts
- dist/cjs/inference/inferTypeFromValues.d.ts
- dist/cjs/inference/types.d.ts
- dist/cjs/notification/AddNotificationContext.d.ts
- dist/cjs/notification/CloseNotificationContext.d.ts
- dist/cjs/notification/NotificationContext.d.ts
- dist/cjs/notification/NotificationContextProvider.d.ts
- dist/cjs/notification/types.d.ts
- dist/cjs/notification/useAddNotificationContext.d.ts
- dist/cjs/notification/useCloseNotification.d.ts
- dist/cjs/notification/useNotificationContext.d.ts
- dist/cjs/notification/useNotify.d.ts
- dist/cjs/preferences/PreferenceKeyContext.d.ts
- dist/cjs/preferences/PreferencesEditorContext.d.ts
- dist/cjs/preferences/PreferencesEditorContextProvider.d.ts
- dist/cjs/preferences/usePreference.d.ts
- dist/cjs/preferences/usePreferenceInput.d.ts
- dist/cjs/preferences/usePreferencesEditor.d.ts
- dist/cjs/preferences/useSetInspectorTitle.d.ts
- dist/cjs/routing/AdminRouter.d.ts
- dist/cjs/routing/BasenameContextProvider.d.ts
- dist/cjs/routing/RestoreScrollPosition.d.ts
- dist/cjs/routing/TestMemoryRouter.d.ts
- dist/cjs/routing/types.d.ts
- dist/cjs/routing/useBasename.d.ts
- dist/cjs/routing/useCreatePath.d.ts
- dist/cjs/routing/useGetPathForRecord.d.ts
- dist/cjs/routing/useGetPathForRecordCallback.d.ts
- dist/cjs/routing/useRedirect.d.ts
- dist/cjs/routing/useResetErrorBoundaryOnLocationChange.d.ts
- dist/cjs/routing/useRestoreScrollPosition.d.ts
- dist/cjs/routing/useScrollToTop.d.ts
- dist/cjs/routing/useSplatPathBase.d.ts
- dist/cjs/store/StoreContext.d.ts
- dist/cjs/store/StoreContextProvider.d.ts
- dist/cjs/store/StoreSetter.d.ts
- dist/cjs/store/localStorageStore.d.ts
- dist/cjs/store/memoryStore.d.ts
- dist/cjs/store/types.d.ts
- dist/cjs/store/useRemoveFromStore.d.ts
- dist/cjs/store/useRemoveItemsFromStore.d.ts
- dist/cjs/store/useResetStore.d.ts
- dist/cjs/store/useStore.d.ts
- dist/cjs/store/useStoreContext.d.ts
- dist/cjs/types.d.ts
- dist/cjs/util/FieldTitle.d.ts
- dist/cjs/util/Ready.d.ts
- dist/cjs/util/asyncDebounce.d.ts
- dist/cjs/util/escapePath.d.ts
- dist/cjs/util/getFieldLabelTranslationArgs.d.ts
- dist/cjs/util/getMutationMode.d.ts
- dist/cjs/util/hooks.d.ts
- dist/cjs/util/mergeRefs.d.ts
- dist/cjs/util/removeEmpty.d.ts
- dist/cjs/util/removeKey.d.ts
- dist/cjs/util/shallowEqual.d.ts
- dist/cjs/util/useCheckForApplicationUpdate.d.ts
- dist/cjs/util/useDebouncedEvent.d.ts
- dist/cjs/util/useEvent.d.ts
- dist/cjs/util/useFieldValue.d.ts
- dist/cjs/util/useWhyDidYouUpdate.d.ts
- dist/cjs/util/warning.d.ts
Dependencies (10)
Dev Dependencies (21)
Peer Dependencies (5)
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 19811 ms. - Missing or incorrect documentation? Open an issue for this package.