-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathReferenceManyCountBase.tsx
More file actions
87 lines (81 loc) · 2.6 KB
/
Copy pathReferenceManyCountBase.tsx
File metadata and controls
87 lines (81 loc) · 2.6 KB
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
import React from 'react';
import {
useReferenceManyFieldController,
type UseReferenceManyFieldControllerParams,
} from './useReferenceManyFieldController';
import { useTimeout } from '../../util/hooks';
import { RecordContextProvider } from '../record';
/**
* Fetch and render the number of records related to the current one
*
* Relies on dataProvider.getManyReference() returning a total property
*
* @example // Display the number of comments for the current post
* <ReferenceManyCountBase reference="comments" target="post_id" />
*
* @example // Display the number of published comments for the current post
* <ReferenceManyCountBase reference="comments" target="post_id" filter={{ is_published: true }} />
*/
export const ReferenceManyCountBase = (props: ReferenceManyCountBaseProps) => {
const {
children,
loading,
error,
offline,
timeout = 1000,
...rest
} = props;
const oneSecondHasPassed = useTimeout(timeout);
const {
isPaused,
isPending,
error: fetchError,
total,
} = useReferenceManyFieldController<any, any>({
...rest,
page: 1,
perPage: 1,
});
const shouldRenderLoading =
isPending && !isPaused && loading !== undefined && loading !== false;
const shouldRenderOffline =
isPending && isPaused && offline !== undefined && offline !== false;
const shouldRenderError =
!isPending && fetchError && error !== undefined && error !== false;
const totalRecord = React.useMemo(() => ({ id: 'count', total }), [total]);
const renderChildren =
typeof children === 'function' ? children(totalRecord) : children;
return (
<>
{shouldRenderLoading ? (
oneSecondHasPassed ? (
loading
) : null
) : shouldRenderOffline ? (
offline
) : shouldRenderError ? (
error
) : children != null ? (
<RecordContextProvider value={totalRecord}>
{renderChildren}
</RecordContextProvider>
) : (
total
)}
</>
);
};
export interface ReferenceManyCountRecord {
id: string;
total: number | undefined;
}
export interface ReferenceManyCountBaseProps
extends UseReferenceManyFieldControllerParams {
children?:
| React.ReactNode
| ((record: ReferenceManyCountRecord) => React.ReactNode);
timeout?: number;
loading?: React.ReactNode;
error?: React.ReactNode;
offline?: React.ReactNode;
}