-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #5829 from marmelab/ensure-resource-definition-ove…
…rridable-with-props Ensure Resource Definition is Overridable with Props
- Loading branch information
Showing
1 changed file
with
27 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,39 @@ | ||
import { useSelector } from 'react-redux'; | ||
import merge from 'lodash/merge'; | ||
import { getResources } from '../reducer'; | ||
import { ResourceDefinition } from '../types'; | ||
import { useResourceContext } from './useResourceContext'; | ||
import { useMemo } from 'react'; | ||
|
||
/** | ||
* Hook which returns the definition of the requested resource | ||
*/ | ||
export const useResourceDefinition = (props): ResourceDefinition => { | ||
export const useResourceDefinition = ( | ||
props: UseResourceDefinitionOptions | ||
): ResourceDefinition => { | ||
const resource = useResourceContext(props); | ||
const resources = useSelector(getResources); | ||
const { hasCreate, hasEdit, hasList, hasShow } = props; | ||
|
||
return resources.find(r => r?.name === resource) || props; | ||
const definition = useMemo(() => { | ||
const definitionFromRedux = resources.find(r => r?.name === resource); | ||
return merge({}, definitionFromRedux, { | ||
hasCreate, | ||
hasEdit, | ||
hasList, | ||
hasShow, | ||
}); | ||
}, [resource, resources, hasCreate, hasEdit, hasList, hasShow]); | ||
|
||
return definition; | ||
}; | ||
|
||
export interface UseResourceDefinitionOptions { | ||
readonly resource?: string; | ||
readonly options?: any; | ||
readonly hasList?: boolean; | ||
readonly hasEdit?: boolean; | ||
readonly hasShow?: boolean; | ||
readonly hasCreate?: boolean; | ||
readonly icon?: any; | ||
} |