-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
useShowController.ts
88 lines (81 loc) · 2.36 KB
/
useShowController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import inflection from 'inflection';
import useVersion from './useVersion';
import { useCheckMinimumRequiredProps } from './checkMinimumRequiredProps';
import { Record, Identifier } from '../types';
import { useGetOne } from '../dataProvider';
import { useTranslate } from '../i18n';
import { useNotify, useRedirect, useRefresh } from '../sideEffect';
import { CRUD_GET_ONE } from '../actions';
export interface ShowProps {
basePath: string;
hasCreate?: boolean;
hasedit?: boolean;
hasShow?: boolean;
hasList?: boolean;
id: Identifier;
resource: string;
[key: string]: any;
}
export interface ShowControllerProps {
loading: boolean;
loaded: boolean;
defaultTitle: string;
resource: string;
basePath: string;
record?: Record;
version: number;
}
/**
* Prepare data for the Show view
*
* @param {Object} props The props passed to the Show component.
*
* @return {Object} controllerProps Fetched data and callbacks for the Show view
*
* @example
*
* import { useShowController } from 'react-admin';
* import ShowView from './ShowView';
*
* const MyShow = props => {
* const controllerProps = useShowController(props);
* return <ShowView {...controllerProps} {...props} />;
* }
*/
const useShowController = (props: ShowProps): ShowControllerProps => {
useCheckMinimumRequiredProps('Show', ['basePath', 'resource'], props);
const { basePath, id, resource } = props;
const translate = useTranslate();
const notify = useNotify();
const redirect = useRedirect();
const refresh = useRefresh();
const version = useVersion();
const { data: record, loading, loaded } = useGetOne(resource, id, {
version, // used to force reload
action: CRUD_GET_ONE,
onFailure: () => {
notify('ra.notification.item_doesnt_exist', 'warning');
redirect('list', basePath);
refresh();
},
});
const resourceName = translate(`resources.${resource}.name`, {
smart_count: 1,
_: inflection.humanize(inflection.singularize(resource)),
});
const defaultTitle = translate('ra.page.show', {
name: `${resourceName}`,
id,
record,
});
return {
loading,
loaded,
defaultTitle,
resource,
basePath,
record,
version,
};
};
export default useShowController;