-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathwithCurrentUserPersonalDetails.tsx
67 lines (56 loc) · 2.73 KB
/
withCurrentUserPersonalDetails.tsx
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
import type {ComponentType, ForwardedRef, RefAttributes} from 'react';
import React, {useMemo} from 'react';
import type {OnyxEntry} from 'react-native-onyx';
import {withOnyx} from 'react-native-onyx';
import getComponentDisplayName from '@libs/getComponentDisplayName';
import personalDetailsPropType from '@pages/personalDetailsPropType';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {PersonalDetails, Session} from '@src/types/onyx';
import {usePersonalDetails} from './OnyxProvider';
type CurrentUserPersonalDetails = PersonalDetails | Record<string, never>;
type OnyxProps = {
/** Session of the current user */
session: OnyxEntry<Session>;
};
type HOCProps = {
currentUserPersonalDetails: CurrentUserPersonalDetails;
};
type WithCurrentUserPersonalDetailsProps = OnyxProps & HOCProps;
// TODO: remove when all components that use it will be migrated to TS
const withCurrentUserPersonalDetailsPropTypes = {
currentUserPersonalDetails: personalDetailsPropType,
};
const withCurrentUserPersonalDetailsDefaultProps: HOCProps = {
currentUserPersonalDetails: {},
};
export default function <TProps extends WithCurrentUserPersonalDetailsProps, TRef>(
WrappedComponent: ComponentType<TProps & RefAttributes<TRef>>,
): ComponentType<Omit<Omit<TProps, keyof HOCProps> & RefAttributes<TRef>, keyof OnyxProps>> {
function WithCurrentUserPersonalDetails(props: Omit<TProps, keyof HOCProps>, ref: ForwardedRef<TRef>) {
const personalDetails = usePersonalDetails() ?? CONST.EMPTY_OBJECT;
const accountID = props.session?.accountID ?? 0;
const accountPersonalDetails = personalDetails?.[accountID];
const currentUserPersonalDetails: CurrentUserPersonalDetails = useMemo(
() => (accountPersonalDetails ? {...accountPersonalDetails, accountID} : {}) as CurrentUserPersonalDetails,
[accountPersonalDetails, accountID],
);
return (
<WrappedComponent
// eslint-disable-next-line react/jsx-props-no-spreading
{...(props as TProps)}
ref={ref}
currentUserPersonalDetails={currentUserPersonalDetails}
/>
);
}
WithCurrentUserPersonalDetails.displayName = `WithCurrentUserPersonalDetails(${getComponentDisplayName(WrappedComponent)})`;
const withCurrentUserPersonalDetails = React.forwardRef(WithCurrentUserPersonalDetails);
return withOnyx<Omit<TProps, keyof HOCProps> & RefAttributes<TRef>, OnyxProps>({
session: {
key: ONYXKEYS.SESSION,
},
})(withCurrentUserPersonalDetails);
}
export {withCurrentUserPersonalDetailsPropTypes, withCurrentUserPersonalDetailsDefaultProps};
export type {WithCurrentUserPersonalDetailsProps};