Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Migrate withReportAndReportActionOrNotFound from withOnyx to useOnyx #49460

Merged
merged 26 commits into from
Oct 7, 2024

Conversation

etCoderDysto
Copy link
Contributor

@etCoderDysto etCoderDysto commented Sep 19, 2024

Details

Fixed Issues

$ #49107
PROPOSAL: #49107 (comment)

Tests

Test 1

  1. Navigate to any chat
  2. Split expense
  3. Open split expense details
  • Verify that nothing is broken. Compare it with production.

Test 2
4. After completing step 3, copy the URL while split expense details page is opened
5. Add few number at the end of the URL
6. Copy the edited URL
7. Send it to any message
8. Open the URL

  • Verify that not found page is displayed

Test 3

  1. Navigate 1:1 chat
  2. Right click on another users message
  3. Click on flag as offensive
  4. Select one of the listed reasons
  • Verify that nothing is broken. Compare it with production.
  • Verify that no errors appear in the JS console

Offline tests

Same as test stpes

QA Steps

Same as test steps

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I verified the translation was requested/reviewed in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android.mp4

Not found page test

Android.mp4
Android: mWeb Chrome
moblie.chrome.mp4

Not found page test
https://github.com/user-attachments/assets/2d6c3eaa-abaa-4f0a-92df-1176aea33780

iOS: Native
ios.mp4

Not found page test

IOS.mp4
iOS: mWeb Safari
safari.mp4

Not found page test

Screen.Recording.2024-10-07.at.12.19.58.in.the.afternoon.mp4
MacOS: Chrome / Safari
Web.mp4

Not found page test

Desktop.web.mp4
MacOS: Desktop
Desktop.mp4

@etCoderDysto etCoderDysto marked this pull request as ready for review September 19, 2024 14:57
@etCoderDysto etCoderDysto requested a review from a team as a code owner September 19, 2024 14:57
@melvin-bot melvin-bot bot requested a review from hoangzinh September 19, 2024 14:57
Copy link

melvin-bot bot commented Sep 19, 2024

@hoangzinh Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also think we should take a closer look at the props we're drilling down and only pass those that are actually used by wrapped components. That does require changing some other consuming files, but overall it's a big simplification.

  • pass down only report, reportAction (i.e: the reportAction linked in the route), parentReport, parentReportAction
  • Remove Onyx props
  • Remove duplicate props from withOnyx in consuming components
Full diff
diff --git a/src/pages/FlagCommentPage.tsx b/src/pages/FlagCommentPage.tsx
index c54edae479d..3e16bc76ba4 100644
--- a/src/pages/FlagCommentPage.tsx
+++ b/src/pages/FlagCommentPage.tsx
@@ -1,7 +1,6 @@
 import type {StackScreenProps} from '@react-navigation/stack';
-import React, {useCallback} from 'react';
+import React from 'react';
 import {View} from 'react-native';
-import type {OnyxEntry} from 'react-native-onyx';
 import type {SvgProps} from 'react-native-svg';
 import type {ValueOf} from 'type-fest';
 import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
@@ -20,18 +19,12 @@ import * as Report from '@userActions/Report';
 import * as Session from '@userActions/Session';
 import CONST from '@src/CONST';
 import type SCREENS from '@src/SCREENS';
-import type * as OnyxTypes from '@src/types/onyx';
 import withReportAndReportActionOrNotFound from './home/report/withReportAndReportActionOrNotFound';
 import type {WithReportAndReportActionOrNotFoundProps} from './home/report/withReportAndReportActionOrNotFound';
 
-type FlagCommentPageWithOnyxProps = {
-    /** The report action from the parent report */
-    parentReportAction: OnyxEntry<OnyxTypes.ReportAction>;
-};
-
 type FlagCommentPageNavigationProps = StackScreenProps<FlagCommentNavigatorParamList, typeof SCREENS.FLAG_COMMENT_ROOT>;
 
-type FlagCommentPageProps = WithReportAndReportActionOrNotFoundProps & FlagCommentPageNavigationProps & FlagCommentPageWithOnyxProps;
+type FlagCommentPageProps = WithReportAndReportActionOrNotFoundProps & FlagCommentPageNavigationProps;
 
 type Severity = ValueOf<typeof CONST.MODERATION>;
 
@@ -53,7 +46,7 @@ function getReportID(route: FlagCommentPageNavigationProps['route']) {
     return route.params.reportID.toString();
 }
 
-function FlagCommentPage({parentReportAction, route, report, parentReport, reportActions}: FlagCommentPageProps) {
+function FlagCommentPage({route, report, reportAction, parentReport, parentReportAction}: FlagCommentPageProps) {
     const styles = useThemeStyles();
     const {translate} = useLocalize();
 
@@ -108,24 +101,8 @@ function FlagCommentPage({parentReportAction, route, report, parentReport, repor
         },
     ];
 
-    const getActionToFlag = useCallback((): OnyxTypes.ReportAction | null => {
-        let reportAction = reportActions?.[`${route.params.reportActionID.toString()}`];
-
-        // Handle threads if needed
-        if (reportAction?.reportActionID === undefined && parentReportAction) {
-            reportAction = parentReportAction;
-        }
-
-        if (!reportAction) {
-            return null;
-        }
-
-        return reportAction;
-    }, [reportActions, route.params.reportActionID, parentReportAction]);
-
     const flagComment = (severity: Severity) => {
         let reportID: string | undefined = getReportID(route);
-        const reportAction = getActionToFlag();
 
         // Handle threads if needed
         if (ReportUtils.isChatThread(report) && reportAction?.reportActionID === parentReportAction?.reportActionID) {
@@ -158,7 +135,7 @@ function FlagCommentPage({parentReportAction, route, report, parentReport, repor
             testID={FlagCommentPage.displayName}
         >
             {({safeAreaPaddingBottomStyle}) => (
-                <FullPageNotFoundView shouldShow={!ReportUtils.shouldShowFlagComment(getActionToFlag(), report)}>
+                <FullPageNotFoundView shouldShow={!ReportUtils.shouldShowFlagComment(reportAction, report)}>
                     <HeaderWithBackButton title={translate('reportActionContextMenu.flagAsOffensive')} />
                     <ScrollView
                         contentContainerStyle={safeAreaPaddingBottomStyle}
diff --git a/src/pages/home/report/withReportAndReportActionOrNotFound.tsx b/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
index fcf7af4b42b..db6a37764b8 100644
--- a/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
+++ b/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
@@ -1,8 +1,8 @@
 /* eslint-disable rulesdir/no-negated-variables */
 import type {StackScreenProps} from '@react-navigation/stack';
 import type {ComponentType, ForwardedRef, RefAttributes} from 'react';
-import React, {useCallback, useEffect} from 'react';
-import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
+import React, {useEffect, useMemo} from 'react';
+import type {OnyxEntry} from 'react-native-onyx';
 import {useOnyx} from 'react-native-onyx';
 import FullscreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
 import useResponsiveLayout from '@hooks/useResponsiveLayout';
@@ -16,35 +16,23 @@ import type SCREENS from '@src/SCREENS';
 import type * as OnyxTypes from '@src/types/onyx';
 import {isEmptyObject} from '@src/types/utils/EmptyObject';
 
-type OnyxProps = {
+type WithReportAndReportActionOrNotFoundProps = StackScreenProps<
+    FlagCommentNavigatorParamList & SplitDetailsNavigatorParamList,
+    typeof SCREENS.FLAG_COMMENT_ROOT | typeof SCREENS.SPLIT_DETAILS.ROOT
+> & {
     /** The report currently being looked at */
-    report: OnyxEntry<OnyxTypes.Report>;
+    report: OnyxTypes.Report;
+
+    /** The reportAction from the current route */
+    reportAction: OnyxTypes.ReportAction;
 
     /** The parent report if the current report is a thread and it has a parent */
     parentReport: OnyxEntry<OnyxTypes.Report>;
 
-    /** The report metadata */
-    reportMetadata: OnyxEntry<OnyxTypes.ReportMetadata>;
-
-    /** Array of report actions for this report */
-    reportActions: OnyxEntry<OnyxTypes.ReportActions>;
-
     /** The report's parentReportAction */
     parentReportAction: NonNullable<OnyxEntry<OnyxTypes.ReportAction>> | null;
-
-    /** The policies which the user has access to */
-    policies: OnyxCollection<OnyxTypes.Policy>;
-
-    /** Beta features list */
-    betas: OnyxEntry<OnyxTypes.Beta[]>;
-
-    /** Indicated whether the report data is loading */
-    isLoadingReportData: OnyxEntry<boolean>;
 };
 
-type WithReportAndReportActionOrNotFoundProps = OnyxProps &
-    StackScreenProps<FlagCommentNavigatorParamList & SplitDetailsNavigatorParamList, typeof SCREENS.FLAG_COMMENT_ROOT | typeof SCREENS.SPLIT_DETAILS.ROOT>;
-
 export default function <TProps extends WithReportAndReportActionOrNotFoundProps, TRef>(
     WrappedComponent: ComponentType<TProps & RefAttributes<TRef>>,
 ): ComponentType<TProps & RefAttributes<TRef>> {
@@ -66,7 +54,8 @@ export default function <TProps extends WithReportAndReportActionOrNotFoundProps
             },
             canEvict: false,
         });
-        const getReportAction = useCallback(() => {
+
+        const linkedReportAction = useMemo(() => {
             let reportAction: OnyxEntry<OnyxTypes.ReportAction> = reportActions?.[`${props.route.params.reportActionID}`];
 
             // Handle threads if needed
@@ -75,16 +64,14 @@ export default function <TProps extends WithReportAndReportActionOrNotFoundProps
             }
 
             return reportAction;
-        }, [reportActions, props.route.params.reportActionID, parentReportAction]);
-
-        const reportAction = getReportAction();
+        }, [parentReportAction, props.route.params.reportActionID, reportActions]);
 
         const {shouldUseNarrowLayout} = useResponsiveLayout();
 
         // For small screen, we don't call openReport API when we go to a sub report page by deeplink
         // So we need to call openReport here for small screen
         useEffect(() => {
-            if (!shouldUseNarrowLayout || (!isEmptyObject(report) && !isEmptyObject(reportAction))) {
+            if (!shouldUseNarrowLayout || (!isEmptyObject(report) && !isEmptyObject(linkedReportAction))) {
                 return;
             }
             Report.openReport(props.route.params.reportID);
@@ -93,7 +80,7 @@ export default function <TProps extends WithReportAndReportActionOrNotFoundProps
 
         // Perform all the loading checks
         const isLoadingReport = isLoadingReportData && !report?.reportID;
-        const isLoadingReportAction = isEmptyObject(reportActions) || (reportMetadata?.isLoadingInitialReportActions && isEmptyObject(getReportAction()));
+        const isLoadingReportAction = isEmptyObject(reportActions) || (reportMetadata?.isLoadingInitialReportActions && isEmptyObject(linkedReportAction));
         const shouldHideReport = !isLoadingReport && (!report?.reportID || !ReportUtils.canAccessReport(report, policies, betas));
 
         // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
@@ -104,14 +91,18 @@ export default function <TProps extends WithReportAndReportActionOrNotFoundProps
         // Perform the access/not found checks
         // Be sure to avoid showing the not-found page while the parent report actions are still being read from Onyx. The parentReportAction will be undefined while it's being read from Onyx
         // and then reportAction will either be a valid parentReportAction or an empty object. In the case of an empty object, then it's OK to show the not-found page.
-        if (shouldHideReport || (parentReportAction !== undefined && isEmptyObject(reportAction))) {
+        if (shouldHideReport || (parentReportAction !== undefined && isEmptyObject(linkedReportAction))) {
             return <NotFoundPage />;
         }
 
         return (
             <WrappedComponent
                 // eslint-disable-next-line react/jsx-props-no-spreading
-                {...{...props, report, parentReport, reportMetadata, isLoadingReportData, betas, policies, reportActions, parentReportAction}}
+                {...props}
+                report={report}
+                reportAction={linkedReportAction}
+                parentReport={parentReport}
+                parentReportAction={parentReportAction}
                 ref={ref}
             />
         );
diff --git a/src/pages/iou/SplitBillDetailsPage.tsx b/src/pages/iou/SplitBillDetailsPage.tsx
index efefc8ccc9e..95a539f8cd4 100644
--- a/src/pages/iou/SplitBillDetailsPage.tsx
+++ b/src/pages/iou/SplitBillDetailsPage.tsx
@@ -1,9 +1,7 @@
 import type {StackScreenProps} from '@react-navigation/stack';
-import type {ComponentType} from 'react';
-import React, {useCallback, useMemo, useState} from 'react';
+import React, {useCallback, useState} from 'react';
 import {View} from 'react-native';
-import {withOnyx} from 'react-native-onyx';
-import type {OnyxEntry} from 'react-native-onyx';
+import {useOnyx} from 'react-native-onyx';
 import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
 import HeaderWithBackButton from '@components/HeaderWithBackButton';
 import Icon from '@components/Icon';
@@ -26,46 +24,25 @@ import * as IOU from '@userActions/IOU';
 import CONST from '@src/CONST';
 import ONYXKEYS from '@src/ONYXKEYS';
 import type SCREENS from '@src/SCREENS';
-import type {PersonalDetailsList, Report, ReportAction, Session, Transaction} from '@src/types/onyx';
 import type {Participant} from '@src/types/onyx/IOU';
-import type {ReportActions} from '@src/types/onyx/ReportAction';
 import {isEmptyObject} from '@src/types/utils/EmptyObject';
 
-type SplitBillDetailsPageTransactionOnyxProps = {
-    /** The current transaction */
-    transaction: OnyxEntry<Transaction>;
+type SplitBillDetailsPageProps = WithReportAndReportActionOrNotFoundProps & StackScreenProps<SplitDetailsNavigatorParamList, typeof SCREENS.SPLIT_DETAILS.ROOT>;
 
-    /** The draft transaction that holds data to be persisited on the current transaction */
-    draftTransaction: OnyxEntry<Transaction>;
-};
-
-type SplitBillDetailsPageOnyxPropsWithoutTransaction = {
-    /** The personal details of the person who is logged in */
-    personalDetails: OnyxEntry<PersonalDetailsList>;
-
-    /** The active report */
-    report: OnyxEntry<Report>;
-
-    /** Array of report actions for this report */
-    reportActions: OnyxEntry<ReportActions>;
-
-    /** Session info for the currently logged in user. */
-    session: OnyxEntry<Session>;
-};
-
-type SplitBillDetailsPageOnyxProps = SplitBillDetailsPageTransactionOnyxProps & SplitBillDetailsPageOnyxPropsWithoutTransaction;
-
-type SplitBillDetailsPageProps = WithReportAndReportActionOrNotFoundProps &
-    SplitBillDetailsPageOnyxProps &
-    StackScreenProps<SplitDetailsNavigatorParamList, typeof SCREENS.SPLIT_DETAILS.ROOT>;
-
-function SplitBillDetailsPage({personalDetails, report, route, reportActions, transaction, draftTransaction, session}: SplitBillDetailsPageProps) {
+function SplitBillDetailsPage({report, reportAction}: SplitBillDetailsPageProps) {
     const styles = useThemeStyles();
-    const reportID = report?.reportID ?? '-1';
     const {translate} = useLocalize();
     const theme = useTheme();
-    const reportAction = useMemo(() => reportActions?.[route.params.reportActionID] ?? ({} as ReportAction), [reportActions, route.params.reportActionID]);
-    const participantAccountIDs = ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction)?.participantAccountIDs ?? [] : [];
+
+    const reportID = report?.reportID ?? '-1';
+    const originalMessage = reportAction && ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction) : undefined;
+    const IOUTransactionID = originalMessage?.IOUTransactionID ?? '-1';
+    const participantAccountIDs = originalMessage?.participantAccountIDs ?? [];
+
+    const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${IOUTransactionID}`);
+    const [draftTransaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${IOUTransactionID}`);
+    const [personalDetails] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST);
+    const [session] = useOnyx(ONYXKEYS.SESSION);
 
     // In case this is workspace split expense, we manually add the workspace as the second participant of the split expense
     // because we don't save any accountID in the report action's originalMessage other than the payee's accountID
@@ -162,37 +139,4 @@ function SplitBillDetailsPage({personalDetails, report, route, reportActions, tr
 
 SplitBillDetailsPage.displayName = 'SplitBillDetailsPage';
 
-const WrappedComponent = withOnyx<SplitBillDetailsPageProps, SplitBillDetailsPageTransactionOnyxProps>({
-    transaction: {
-        key: ({route, reportActions}) => {
-            const reportAction = reportActions?.[route.params.reportActionID];
-            const originalMessage = reportAction && ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction) : undefined;
-            const IOUTransactionID = reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && originalMessage?.IOUTransactionID ? originalMessage.IOUTransactionID : 0;
-            return `${ONYXKEYS.COLLECTION.TRANSACTION}${IOUTransactionID}`;
-        },
-    },
-    draftTransaction: {
-        key: ({route, reportActions}) => {
-            const reportAction = reportActions?.[route.params.reportActionID];
-            const originalMessage = reportAction && ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction) : undefined;
-            const IOUTransactionID = reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && originalMessage?.IOUTransactionID ? originalMessage.IOUTransactionID : 0;
-            return `${ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT}${IOUTransactionID}`;
-        },
-    },
-})(withReportAndReportActionOrNotFound(SplitBillDetailsPage) as ComponentType<SplitBillDetailsPageProps>);
-
-export default withOnyx<Omit<SplitBillDetailsPageProps, keyof SplitBillDetailsPageTransactionOnyxProps>, SplitBillDetailsPageOnyxPropsWithoutTransaction>({
-    report: {
-        key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT}${route.params.reportID}`,
-    },
-    reportActions: {
-        key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${route.params.reportID}`,
-        canEvict: false,
-    },
-    personalDetails: {
-        key: ONYXKEYS.PERSONAL_DETAILS_LIST,
-    },
-    session: {
-        key: ONYXKEYS.SESSION,
-    },
-})(WrappedComponent);
+export default withReportAndReportActionOrNotFound(SplitBillDetailsPage);

const [betas] = useOnyx(ONYXKEYS.BETAS);
const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const [reportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${props.route.params.reportID}`, {canEvict: false});
const [parentReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : 0}`, {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const [parentReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : 0}`, {
const [parentReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : '-1'}`, {

const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const [reportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${props.route.params.reportID}`, {canEvict: false});
const [parentReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : 0}`, {
selector: (parentReportActions: OnyxEntry<OnyxTypes.ReportActions>): NonNullable<OnyxEntry<OnyxTypes.ReportAction>> | null => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can simplify the selector types by relying on the better type inference we get from useOnyx:

diff --git a/src/pages/home/report/withReportAndReportActionOrNotFound.tsx b/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
index fcf7af4b42b..52a4c389337 100644
--- a/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
+++ b/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
@@ -56,8 +56,8 @@ export default function <TProps extends WithReportAndReportActionOrNotFoundProps
         const [betas] = useOnyx(ONYXKEYS.BETAS);
         const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
         const [reportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${props.route.params.reportID}`, {canEvict: false});
-        const [parentReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : 0}`, {
-            selector: (parentReportActions: OnyxEntry<OnyxTypes.ReportActions>): NonNullable<OnyxEntry<OnyxTypes.ReportAction>> | null => {
+        const [parentReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : '-1'}`, {
+            selector: (parentReportActions) => {
                 const parentReportActionID = report?.parentReportActionID;
                 if (!parentReportActionID) {
                     return null;

return <NotFoundPage />;
}

return (
<WrappedComponent
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
{...{...props, report, parentReport, reportMetadata, isLoadingReportData, betas, policies, reportActions, parentReportAction}}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's simplify this and only use the minimum amount of spread props:

diff --git a/src/pages/home/report/withReportAndReportActionOrNotFound.tsx b/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
index fcf7af4b42b..2bb555ed550 100644
--- a/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
+++ b/src/pages/home/report/withReportAndReportActionOrNotFound.tsx
@@ -111,7 +111,15 @@ export default function <TProps extends WithReportAndReportActionOrNotFoundProps
         return (
             <WrappedComponent
                 // eslint-disable-next-line react/jsx-props-no-spreading
-                {...{...props, report, parentReport, reportMetadata, isLoadingReportData, betas, policies, reportActions, parentReportAction}}
+                {...props}
+                report={report}
+                parentReport={parentReport}
+                reportMetadata={reportMetadata}
+                isLoadingReportData={isLoadingReportData}
+                betas={betas}
+                policies={policies}
+                reportActions={reportActions}
+                parentReportAction={parentReportAction}
                 ref={ref}
             />
         );

@hoangzinh
Copy link
Contributor

@etCoderDysto, do you have any updates on @roryabraham's feedback above?

@etCoderDysto
Copy link
Contributor Author

Yes, @hoangzinh. I am almost done. It will be ready for further review today.

@etCoderDysto
Copy link
Contributor Author

@hoangzinh @roryabraham I have applied the suggested chagnes.

@hoangzinh
Copy link
Contributor

Thanks for the updates. I will review today

roryabraham
roryabraham previously approved these changes Sep 28, 2024
Copy link
Contributor

@roryabraham roryabraham left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍🏼


const reportID = report?.reportID ?? '-1';
const originalMessage = reportAction && ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction) : undefined;
const IOUTransactionID = originalMessage?.IOUTransactionID ?? '-1';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that what we have here is correct. We still check for the reportAction being of type IOU on the previous line when we get the originalMessage


const reportID = report?.reportID ?? '-1';
const originalMessage = reportAction && ReportActionsUtils.isMoneyRequestAction(reportAction) ? ReportActionsUtils.getOriginalMessage(reportAction) : undefined;
const IOUTransactionID = originalMessage?.IOUTransactionID ?? '-1';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though @hoangzinh could be right that || would be safer than ?? here to account for the possibility of IOUTransactionID being an empty string. But in practice that should never be the case

@hoangzinh
Copy link
Contributor

hoangzinh commented Oct 2, 2024

@etCoderDysto do you have a ETA for the next review? Thank you.

@etCoderDysto
Copy link
Contributor Author

etCoderDysto commented Oct 3, 2024

@hoangzinh Pr is ready for further review. Sorry for my late reply.

@roryabraham
Copy link
Contributor

LGTM, pulling in @thienlnam to take over further review in my absence

@hoangzinh
Copy link
Contributor

@etCoderDysto overall, code looks good. Can you add another test steps for "Not found" case? Thank you.

@hoangzinh
Copy link
Contributor

hoangzinh commented Oct 5, 2024

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified tests pass on all platforms & I tested again on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Screen.Recording.2024-10-05.at.14.31.56.mov
Android: mWeb Chrome
Screen.Recording.2024-10-05.at.14.00.48.android.chrome.mov
iOS: Native
Screen.Recording.2024-10-05.at.14.23.39.ios.mov
iOS: mWeb Safari
Screen.Recording.2024-10-05.at.14.30.29.mov
MacOS: Chrome / Safari
Screen.Recording.2024-10-05.at.13.47.16.web.mov
MacOS: Desktop
Screen.Recording.2024-10-05.at.13.50.01.desktop.mov

@hoangzinh
Copy link
Contributor

all yours @thienlnam

@etCoderDysto
Copy link
Contributor Author

@etCoderDysto overall, code looks good. Can you add another test steps for "Not found" case? Thank you.

Great! I will add not found case today

@etCoderDysto
Copy link
Contributor Author

Can you add another test steps for "Not found" case? Thank you.

I have added test steps for not found case, and uploaded videos except desktop. I was not able to open deeplink in desktop. I will try adding desktop when this is pushed to staging.

@hoangzinh
Copy link
Contributor

hoangzinh commented Oct 7, 2024

We can use the Chrome dev tool to open in Desktop. But it's okay, no worry. Thanks for update @etCoderDysto

Copy link
Contributor

@thienlnam thienlnam left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, let's do it!

@thienlnam thienlnam merged commit 00a295f into Expensify:main Oct 7, 2024
18 of 20 checks passed
@OSBotify
Copy link
Contributor

OSBotify commented Oct 7, 2024

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

Copy link
Contributor

github-actions bot commented Oct 7, 2024

🚀 Deployed to staging by https://github.com/thienlnam in version: 9.0.46-0 🚀

platform result
🤖 android 🤖 cancelled 🔪
🖥 desktop 🖥 cancelled 🔪
🍎 iOS 🍎 cancelled 🔪
🕸 web 🕸 success ✅

Copy link
Contributor

github-actions bot commented Oct 9, 2024

🚀 Deployed to production by https://github.com/thienlnam in version: 9.0.46-5 🚀

platform result
🤖 android 🤖 success ✅
🖥 desktop 🖥 success ✅
🍎 iOS 🍎 success ✅
🕸 web 🕸 success ✅

const getReportAction = useCallback(() => {
let reportAction: OnyxEntry<OnyxTypes.ReportAction> = props.reportActions?.[`${props.route.params.reportActionID}`];
const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${props.route.params.reportID}`);
const [parentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${report ? report.parentReportID : '-1'}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong condition is set here, If parentReportID is undefined it is still concatenating to onyx key, resulting in report_undefined key.

#50786

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants