Skip to content

fix storybook issues#90381

Draft
situchan wants to merge 4 commits into
Expensify:mainfrom
situchan:fix-89538
Draft

fix storybook issues#90381
situchan wants to merge 4 commits into
Expensify:mainfrom
situchan:fix-89538

Conversation

@situchan
Copy link
Copy Markdown
Contributor

Explanation of Change

Fixed Issues

$
PROPOSAL:

Tests

  • Verify that no errors appear in the JS console

Offline tests

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."

  • 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
  • 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 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 used JaimeGPT to get English > Spanish translation. I then posted it 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.ts 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 new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • 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.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • 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: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

@situchan
Copy link
Copy Markdown
Contributor Author

@MelvinBot storybook preview background is white. Which PR caused this? It was working in #78416.

bug

@MelvinBot
Copy link
Copy Markdown
Contributor

#78416 caused this. That PR replaced @storybook/addon-essentials with individual addons in .storybook/main.ts:

- addons: ['@storybook/addon-essentials', '@storybook/addon-a11y', '@storybook/addon-webpack5-compiler-babel'],
+ addons: ['@storybook/addon-a11y', '@storybook/addon-webpack5-compiler-babel', '@storybook/addon-docs'],

@storybook/addon-essentials bundles several addons including @storybook/addon-backgrounds, which controls the story canvas background color. When it was replaced with only addon-docs, the backgrounds addon was dropped and the canvas defaulted to white.

Fix: Either add @storybook/addon-backgrounds back to the addons list, or set parameters.backgrounds in .storybook/preview.tsx to configure a dark default background. Note: the appPreviewBg in theme.ts only controls the Storybook manager UI around the canvas, not the canvas itself.

@situchan
Copy link
Copy Markdown
Contributor Author

<InputWrapper
InputComponent={DatePicker}
inputID="dob"
label="Date of Birth"
containerStyles={defaultStyles.mt4}
/>

@MelvinBot this line causes Too many re-renders. React limits the number of renders to prevent an infinite loop..
Which PR regressed this?


<InputWrapper
InputComponent={StateSelector}
inputID="state"
shouldSaveDraft
/>

@MelvinBot this line caused Couldn't find values for screen ScreenWrapper transition status. Are you inside a screen in ScreenWrapper?.
Which PR regressed this?

@MelvinBot
Copy link
Copy Markdown
Contributor

1. "Too many re-renders" (AddressSearch / lines 104-109)

Caused by #49700 (merged 2024-09-27). That PR migrated FormProvider from withOnyx to useOnyx. The story's Template function calls Onyx setters (setIsLoading, setDraftValues, clearErrors) directly in the render body. With withOnyx, these were deferred. With useOnyx (backed by useSyncExternalStore), they trigger synchronous re-renders of FormProvider, creating an infinite loop.

Fix: Move the Onyx setter calls into a useEffect in the Template/WithNativeEventHandler functions.


2. "Couldn't find values for screen ScreenWrapper transition status" (StateSelector / lines 156-160)

Caused by #40369 (merged 2024-04-26). That PR added useScreenWrapperTransitionStatus() to useAnimatedHighlightStyle, which is called unconditionally by MenuItemWithTopDescription, which StateSelector renders. The hook throws when ScreenWrapperStatusContext is undefined, which it is in Storybook since there's no ScreenWrapper provider.

Fix: Add a ScreenWrapperStatusContext.Provider to the Storybook decorator, or make the hook return a default value instead of throwing when context is missing.

@situchan
Copy link
Copy Markdown
Contributor Author

@MelvinBot suggest code changes for #90381 (comment)

@MelvinBot
Copy link
Copy Markdown
Contributor

Here are the suggested code changes for both issues:

1. Fix "Too many re-renders" in Form.stories.tsx

Wrap the Onyx setter calls in useEffect in both Template and WithNativeEventHandler:

- import React, {useState} from 'react';
+ import React, {useEffect, useState} from 'react';
 function Template(props: FormProviderProps & FormProviderOnyxProps) {
-    // Form consumes data from Onyx, so we initialize Onyx with the necessary data here
-    setIsLoading(props.formID, !!props.formState?.isLoading);
-    setDraftValues(props.formID, props.draftValues);
-
-    if (props.formState?.error) {
-        setErrors(props.formID, {error: props.formState.error as string});
-    } else {
-        clearErrors(props.formID);
-    }
+    useEffect(() => {
+        setIsLoading(props.formID, !!props.formState?.isLoading);
+        setDraftValues(props.formID, props.draftValues);
+
+        if (props.formState?.error) {
+            setErrors(props.formID, {error: props.formState.error as string});
+        } else {
+            clearErrors(props.formID);
+        }
+    }, [props.formID, props.formState?.isLoading, props.formState?.error, props.draftValues]);

Apply the same change to WithNativeEventHandler (same pattern at line 180-187).

2. Fix "ScreenWrapper transition status" error in Storybook

Add a ScreenWrapperStatusContext.Provider to the Storybook decorator in .storybook/preview.tsx:

+ import ScreenWrapperStatusContext from '@components/ScreenWrapper/ScreenWrapperStatusContext';
         >
-            <Story />
+            <ScreenWrapperStatusContext.Provider value={{didScreenTransitionEnd: true, isSafeAreaTopPaddingApplied: false, isSafeAreaBottomPaddingApplied: false}}>
+                <Story />
+            </ScreenWrapperStatusContext.Provider>
         </ComposeProviders>

didScreenTransitionEnd: true is the right default since Storybook has no navigation transitions — stories should render as if fully transitioned.

@situchan
Copy link
Copy Markdown
Contributor Author

  1. Fix "Too many re-renders" in Form.stories.tsx

@MelvinBot this happens even after removing this code.
The root cause should be in DatePicker. At a glance, I think we should make that component compilable by React Compiler.

@MelvinBot
Copy link
Copy Markdown
Contributor

Agreed — the root cause is a cyclic useEffect in DatePicker, not the story code at lines 66-74.

Primary cause: DatePickerModal.tsx:47-54 — the useEffect lists selectedDate as a dependency but also calls setSelectedDate(value) inside the effect body. This creates a dependency cycle: effect fires → state changes → effect re-fires.

DatePicker/index.tsx:54-66 has the same pattern with slightly better guards.

Additionally, minDate/maxDate default params create new Date objects on every render in DatePicker, DatePickerModal, and CalendarPicker, defeating reference equality checks and feeding the re-render cycle.

To fix:

  1. Remove selectedDate from the useEffect dependency arrays in both DatePickerModal and DatePicker — the effect should only sync when value changes
  2. Move the default minDate/maxDate to module-level constants so they don't create new objects each render

This should make these components compatible with React Compiler without needing an exclusion.

@situchan
Copy link
Copy Markdown
Contributor Author

@MelvinBot suggest code changes for #90381 (comment)

@MelvinBot
Copy link
Copy Markdown
Contributor

Here are the concrete code changes for all three files:

1. DatePickerModal.tsx — Fix cyclic useEffect + stable defaults

+const DEFAULT_MIN_DATE = setYear(new Date(), CONST.CALENDAR_PICKER.MIN_YEAR);
+const DEFAULT_MAX_DATE = setYear(new Date(), CONST.CALENDAR_PICKER.MAX_YEAR);
+
 function DatePickerModal({
     value,
     defaultValue,
     inputID,
-    minDate = setYear(new Date(), CONST.CALENDAR_PICKER.MIN_YEAR),
-    maxDate = setYear(new Date(), CONST.CALENDAR_PICKER.MAX_YEAR),
+    minDate = DEFAULT_MIN_DATE,
+    maxDate = DEFAULT_MAX_DATE,
     onInputChange,
     ...
 }) {
     const [selectedDate, setSelectedDate] = useState(value ?? defaultValue ?? undefined);
     ...

     useEffect(() => {
-        if (shouldSaveDraft && formID) {
-            setDraftValues(formID, {[inputID]: selectedDate});
-        }
-        if (selectedDate !== value) {
-            setSelectedDate(value);
+        if (value !== undefined) {
+            setSelectedDate(value);
         }
-    }, [formID, inputID, selectedDate, shouldSaveDraft, value]);
+    }, [value]);
+
+    useEffect(() => {
+        if (shouldSaveDraft && formID) {
+            setDraftValues(formID, {[inputID]: selectedDate});
+        }
+    }, [formID, inputID, selectedDate, shouldSaveDraft]);

Split into two effects: one syncs selectedDate from value (no selectedDate in deps), the other saves drafts.

2. DatePicker/index.tsx — Same pattern

+const DEFAULT_MIN_DATE = setYear(new Date(), CONST.CALENDAR_PICKER.MIN_YEAR);
+const DEFAULT_MAX_DATE = setYear(new Date(), CONST.CALENDAR_PICKER.MAX_YEAR);
+
 function DatePicker({
     ...
-    minDate = setYear(new Date(), CONST.CALENDAR_PICKER.MIN_YEAR),
-    maxDate = setYear(new Date(), CONST.CALENDAR_PICKER.MAX_YEAR),
+    minDate = DEFAULT_MIN_DATE,
+    maxDate = DEFAULT_MAX_DATE,
     ...
 }) {
     ...

     useEffect(() => {
-        if (shouldSaveDraft && formID) {
-            setDraftValues(formID, {[inputID]: selectedDate});
-        }
-        if (selectedDate === value) {
-            return;
-        }
-        if (value === undefined) {
-            return;
+        if (value !== undefined) {
+            setSelectedDate(value);
         }
+    }, [value]);
 
-        setSelectedDate(value);
-    }, [formID, inputID, selectedDate, shouldSaveDraft, value]);
+    useEffect(() => {
+        if (shouldSaveDraft && formID) {
+            setDraftValues(formID, {[inputID]: selectedDate});
+        }
+    }, [formID, inputID, selectedDate, shouldSaveDraft]);

3. CalendarPicker/index.tsx — Stable defaults only

+const DEFAULT_VALUE = new Date();
+const DEFAULT_MIN_DATE = setYear(new Date(), CONST.CALENDAR_PICKER.MIN_YEAR);
+const DEFAULT_MAX_DATE = setYear(new Date(), CONST.CALENDAR_PICKER.MAX_YEAR);
+
 function CalendarPicker({
-    value = new Date(),
-    minDate = setYear(new Date(), CONST.CALENDAR_PICKER.MIN_YEAR),
-    maxDate = setYear(new Date(), CONST.CALENDAR_PICKER.MAX_YEAR),
+    value = DEFAULT_VALUE,
+    minDate = DEFAULT_MIN_DATE,
+    maxDate = DEFAULT_MAX_DATE,
     ...
 }) {

No useEffect changes needed here — CalendarPicker doesn't have the cyclic selectedDate pattern.

@situchan
Copy link
Copy Markdown
Contributor Author

Fix "Too many re-renders" in Form.stories.tsx

@MelvinBot I fixed this by removing

setIsScreenTransitionEnded(false);

The race condition was repetitive setting true/false in setIsScreenTransitionEnded.

But we should not remove this line. What is alternative solution?

@MelvinBot
Copy link
Copy Markdown
Contributor

The root cause isn't line 83 itself — it's that the useNavigation mock returns a new object on every call. Since navigation is a dependency of the useFocusEffect callback in useAutoFocusInput.ts:105, every render creates a new callback, which useFocusEffect (mocked as callback()) immediately invokes, which calls setIsScreenTransitionEnded(false), which triggers another render → infinite loop.

Fix: Hoist the mock object so useNavigation returns a stable reference:

const navigationMock = {
    navigate: () => {},
    getState: () => ({routes: []}),
    addListener,
};

const useNavigation = isJestEnv
    ? realReactNavigation.useNavigation
    : () => navigationMock;

This keeps line 83 intact while breaking the re-render cycle.

@situchan
Copy link
Copy Markdown
Contributor Author

@MelvinBot your fix still not working

@MelvinBot
Copy link
Copy Markdown
Contributor

My previous suggestion was incomplete — the stable navigation mock alone isn't enough. There are two problems in the @react-navigation/native mock:

Problem 1 (my previous suggestion): useNavigation returns a new object per call → unstable navigation ref.

Problem 2 (the main issue): useFocusEffect mock is (callback) => callback() — it calls the callback synchronously during render, not inside a useEffect. This means every render fires the callback, which schedules a setTimeout that sets isScreenTransitionEnded(true), which triggers the useEffect at useAutoFocusInput.ts:72 setting it back to false, re-rendering, and looping.

Fix: Change the useFocusEffect mock to run the callback inside a useEffect (like the real implementation does), and hoist the navigation mock:

import {useEffect} from 'react';

// Stable reference so useNavigation doesn't cause re-renders
const navigationMock = {
    navigate: () => {},
    getState: () => ({routes: []}),
    addListener,
};

const useNavigation = isJestEnv
    ? realReactNavigation.useNavigation
    : () => navigationMock;

// Run callback in useEffect (like real useFocusEffect), not synchronously during render
const useFocusEffect = isJestEnv
    ? realReactNavigation.useFocusEffect
    : (callback: () => (() => void) | void) => {
          // eslint-disable-next-line react-hooks/exhaustive-deps
          useEffect(() => callback(), [callback]);
      };

This way the callback only runs once (since useCallback deps are stable with the hoisted navigation mock), and it runs asynchronously in an effect — not during render — so it won't cause "Too many re-renders".

@situchan
Copy link
Copy Markdown
Contributor Author

Jest Unit Tests / test (job 3) (pull_request)Failing after 6m

@MelvinBot investigate failing tests

@MelvinBot
Copy link
Copy Markdown
Contributor

The TransactionGroupListItemTest failures are caused by your SearchContext.tsx import change from @react-navigation/core to @react-navigation/native.

The test mocks both modules separately. The @react-navigation/core mock (line 46) includes getState, but the @react-navigation/native mock (line 33) does not. Since SearchContext.tsx now imports from @react-navigation/native, navigation.getState() is undefined → TypeError.

Fix: Add getState to the @react-navigation/native useNavigation mock in the test:

useNavigation: () => ({
    navigate: jest.fn(),
    addListener: jest.fn(),
    getState: jest.fn(() => undefined),
}),

Also, regarding my earlier comment — the same principle applies to your global mock at __mocks__/@react-navigation/native/index.ts:21-27. Hoist the return value to a module-level constant so useNavigation() returns a stable reference (fixes the Storybook re-render issue).

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.

2 participants