forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCurrentReportID.tsx
63 lines (52 loc) · 2.27 KB
/
useCurrentReportID.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
import type {NavigationState} from '@react-navigation/native';
import React, {createContext, useCallback, useContext, useMemo, useState} from 'react';
import Navigation from '@libs/Navigation/Navigation';
type CurrentReportIDContextValue = {
updateCurrentReportID: (state: NavigationState) => void;
currentReportID: string | undefined;
};
type CurrentReportIDContextProviderProps = {
/** Actual content wrapped by this component */
children: React.ReactNode;
};
const CurrentReportIDContext = createContext<CurrentReportIDContextValue | null>(null);
function CurrentReportIDContextProvider(props: CurrentReportIDContextProviderProps) {
const [currentReportID, setCurrentReportID] = useState<string | undefined>('');
/**
* This function is used to update the currentReportID
* @param state root navigation state
*/
const updateCurrentReportID = useCallback(
(state: NavigationState) => {
const reportID = Navigation.getTopmostReportId(state);
/*
* Make sure we don't make the reportID undefined when switching between the chat list and settings tab.
* This helps prevent unnecessary re-renders.
*/
const params = state?.routes?.[state.index]?.params;
if (params && 'screen' in params && typeof params.screen === 'string' && params.screen.indexOf('Settings_') !== -1) {
return;
}
setCurrentReportID(reportID);
},
[setCurrentReportID],
);
/**
* The context this component exposes to child components
* @returns currentReportID to share between central pane and LHN
*/
const contextValue = useMemo(
(): CurrentReportIDContextValue => ({
updateCurrentReportID,
currentReportID,
}),
[updateCurrentReportID, currentReportID],
);
return <CurrentReportIDContext.Provider value={contextValue}>{props.children}</CurrentReportIDContext.Provider>;
}
CurrentReportIDContextProvider.displayName = 'CurrentReportIDContextProvider';
export default function useCurrentReportID(): CurrentReportIDContextValue | null {
return useContext(CurrentReportIDContext);
}
export {CurrentReportIDContextProvider};
export type {CurrentReportIDContextValue};