From 7e86ff5a5d6905af626d26c614f4e7e0f9bdaa51 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Mon, 2 Nov 2026 20:27:44 +0530 Subject: [PATCH] enh --- apps/user-ui/REACT-DOCTOR-HOME.md | 413 ++++++++++++++++++ .../app/(drawer)/(tabs)/home/index.tsx | 191 +++----- .../(tabs)/home/search-results/index.tsx | 55 ++- apps/user-ui/hooks/useHomeCatalog.ts | 119 +++++ change-log.txt | 38 ++ 5 files changed, 679 insertions(+), 137 deletions(-) create mode 100644 apps/user-ui/REACT-DOCTOR-HOME.md create mode 100644 apps/user-ui/hooks/useHomeCatalog.ts diff --git a/apps/user-ui/REACT-DOCTOR-HOME.md b/apps/user-ui/REACT-DOCTOR-HOME.md new file mode 100644 index 0000000..aa84507 --- /dev/null +++ b/apps/user-ui/REACT-DOCTOR-HOME.md @@ -0,0 +1,413 @@ +# React Doctor — `apps/user-ui/app/(drawer)/(tabs)/home/` + +**Date:** 2026-11-02 +**Tool:** `react-doctor@0.9.22` (millionco) +**Command:** + +```bash +cd apps/user-ui +npx --yes react-doctor@latest --no-telemetry --blocking none --verbose \ + 'app/(drawer)/(tabs)/home' +``` + +**Scope:** 11 files, 1,217 lines — `index.tsx`, `search-results/index.tsx`, +`order-success.tsx`, `_layout.tsx`, `cart.tsx`, `checkout.tsx`, plus the +`product-detail/` and `slot-view/` route files. + +**Scan result:** `✔ Scanned 11 files in 1.3s` — **11 issues** (2 errors, +9 warnings). Score output disabled (`--no-telemetry`). + +**No code was changed for this report.** Each finding below was verified +against the source; verdicts are mine, not the tool's. + +--- + +## Summary + +| # | Rule | Location | Sev | Category | Verdict | +|---|------|----------|-----|----------|---------| +| 1 | `rn-no-scrollview-mapped-list` | `index.tsx:227` | warn | Bugs | False positive (by design) | +| 2 | `duplicate-jsx-subtree` | `index.tsx:444` | warn | Maintainability | True positive (low) | +| 3 | `no-giant-component` | `index.tsx:491` | warn | Maintainability | True positive (medium) | +| 4a | `exhaustive-deps` | `index.tsx:587` | warn | Bugs | True positive (medium) | +| 4b | `exhaustive-deps` | `search-results/index.tsx:75` | warn | Bugs | False positive in practice | +| 5 | `no-impure-state-updater` | `index.tsx:590` | **error** | Bugs | True positive (medium) | +| 6 | `no-side-effect-in-state-updater-function` | `index.tsx:592` | warn | Bugs | Same root cause as #5 | +| 7 | `rerender-memo-before-early-return` | `index.tsx:756` | warn | Performance | True positive (negligible) | +| 8 | `rn-no-falsy-and-render` | `order-success.tsx:47` | **error** | Bugs | False positive | +| 9 | `rn-list-callback-per-row` | `search-results/index.tsx:98` | warn | Bugs | True positive (low) | +| 10 | `expo-lockfile` | `package.json` | warn | Correctness | True positive (repo-level, out of scope) | + +--- + +## Status after the fixes + +Fixed in the working tree (see `change-log.txt`): + +| Finding | Fix | +|---|---| +| #5 / #6 impure updater | `hasMore` is derived (`visibleCount < displayedProducts.length`); `showMore` is a pure updater | +| #4a missing effect deps | the sort effect now lists `getQuickestSlot` and `isSlotsLoaded` | +| #9 inline row handler | memoized `SearchResultItem` owns its `onPress`; the screen passes a stable handler | +| #2 duplicated heading | shared `SectionHeading` used by both sections | +| #3 giant component | catalogue derivation moved to `hooks/useHomeCatalog.ts`; `Dashboard` 346 → ~270 lines | +| #7 memo before early return | `ShowMoreFooter` is a component rendered after the early returns | +| #4b unstable `allProducts` | memoised on `productsData` (tidy, same behaviour) | + +Re-scan of the same folder: **11 issues → 3 issues**. The three that remain are +#1, #8 and #10 above — the two false positives and the lockfile decision. + +```bash +React Doctor — home +3 issues +⚠ react-doctor/rn-no-scrollview-mapped-list index.tsx:227 +✖ react-doctor/rn-no-falsy-and-render order-success.tsx:47 +⚠ react-doctor/expo-lockfile package.json +``` + + +--- + +## 1. `rn-no-scrollview-mapped-list` — `index.tsx:227` + +**Tool says:** `{items.map(...)}` builds every row at +once; use FlatList/FlashList. + +**Code:** + +```tsx +// TagTabStrip + + {routes.map((route, i) => { ... })} + +``` + +**Verdict: false positive.** This is deliberately a horizontal tab strip, not a +data list. It has a comment saying so: + +```tsx +// Fixed, horizontally scrollable tab strip (plain ScrollView — no nesting, +// so it scrolls reliably on Android). Sits OUTSIDE the vertical FlatList. +``` + +The row count is the number of dashboard tags in a region (small, bounded), and +the strip relies on `onLayout` to record each tab's x-position for the +auto-scroll-to-active effect. A `FlatList` would make that position tracking +harder and add virtualization churn for ~5–10 items. + +**Confidence: high.** +**Action:** leave as is. If you want a clean report, add a line-scoped disable +with the reason rather than changing the component. + +--- + +## 2. `duplicate-jsx-subtree` — `index.tsx:444` + +**Tool says:** 2 copies of a 6-node JSX tree, ~9 lines each, in one file. + +**Code:** the section heading in `SlotsSection` (line ~441) and `AllProductsTitle` +(line ~470) are near-identical: + +```tsx + + + … + +… +``` + +**Verdict: true positive.** Low risk, pure presentation. + +**Confidence: high.** +**Suggested fix:** extract `SectionHeading({ title, subtitle, subtitleIndent })` +and use it in both places. The two copies differ only in `mt-2 / mb-[11px]` vs +`mt-2 / mb-4` and the copy text — pass those as props. Behaviour unchanged. + +--- + +## 3. `no-giant-component` — `index.tsx:491` + +**Tool says:** `Dashboard` is over 300 lines. + +**Verdict: true positive.** `Dashboard` spans lines 491–837 (~346 lines). + +It is already better than it used to be — `RenderStore`, `SlotCard`, `TagTabStrip`, +`TagScene`, `ExploreProductItem`, `SlotsSection`, `AllProductsTitle`, +`EmptyCatalog` and the virtualized item renderers are separate components. The +remaining body is mostly: + +- 6 `useState` + 4 central-store selectors + `useProductSlotIdentifier` and the + four data hooks, +- the catalogue memo, +- the sort/effect that produces `displayedProducts`, +- search bar, sections memo, list header/footer memos, +- two early returns, +- the `SectionList` wiring. + +**Confidence: high.** +**Suggested fix (incremental, not one pass):** + +1. Move "catalog → sorted rows" into a custom hook (`useHomeCatalog`) — removes + the effect, the sort and three pieces of state from the component. +2. Move search bar + header/footer into a `` component. +3. Then `Dashboard` is mostly hooks + one ``. + +Items 1 and 2 also fix findings #4a, #5 and #7. + +--- + +## 4a. `exhaustive-deps` — `index.tsx:587` + +**Tool says:** the effect can run with stale `getQuickestSlot` and +`isSlotsLoaded`. + +**Code:** + +```tsx +React.useEffect(() => { + ... + .sort((a, b) => { + const slotA = getQuickestSlot(a.id) + const slotB = getQuickestSlot(b.id) + const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || (isSlotsLoaded && !slotA) + ... + }) + setDisplayedProducts(allSorted) + setVisibleCount(21) + setHasMore(allSorted.length > 21) +}, [products, productSlotsMap]) +``` + +**Verdict: true positive.** `getQuickestSlot` and `isSlotsLoaded` are read but +not listed. Concretely: when slots finish loading, `productSlotsMap` usually +changes and re-runs this, but `isSlotsLoaded` flipping is what makes +"no slot ⇒ out of stock" correct, and it is not a dependency. Ordering can stay +stale for a render (or longer if the map identity happens to be reused). + +**Why it's safe to add them (no loop):** `getQuickestSlot` is already +`useCallback`-memoized on `[slots, productSlotsMap]` +(`apps/user-ui/hooks/useProductSlotIdentifier.ts`), and the effect writes only +`displayedProducts` / `visibleCount` / `hasMore`, none of which it depends on. So +adding the deps cannot self-trigger. + +**Confidence: high.** +**Suggested fix:** `}, [products, productSlotsMap, getQuickestSlot, isSlotsLoaded])`. + +--- + +## 4b. `exhaustive-deps` — `search-results/index.tsx:75` + +**Tool says:** `allProducts` is rebuilt every render, so the `useMemo` runs every +time. + +**Code:** + +```tsx +const allProducts = productsData?.products || [] +... +const products = useMemo(() => { ...fuse... }, [allProducts, debouncedQuery]) +``` + +**Verdict: false positive in practice.** When data is loaded, +`productsData.products` is a stable reference (`useAllProducts` memoizes +`mergedData`), so `||` returns the same array and the memo holds. The `[]` +fallback is only created while `productsData` is undefined — at which point the +list is empty anyway. The extra memo pass costs nothing measurable. + +**Confidence: high.** +**Optional tidy:** `const allProducts = useMemo(() => productsData?.products ?? [], [productsData])`. +Do it only if you want the warning gone; no user-visible change either way. + +--- + +## 5 & 6. State updater with side effects — `index.tsx:590` / `:592` + +**Tool says (error):** "This state updater performs the nested state update +`setHasMore()`." And a second warning for the side effect itself. + +**Code:** + +```tsx +const handleShowMore = useCallback(() => { + setVisibleCount((prev) => { + const next = prev + 21; + setHasMore(next < displayedProducts.length); // side effect inside updater + return next; + }); +}, [displayedProducts.length]); +``` + +**Verdict: true positive, and it is real.** React may invoke a state updater more +than once (StrictMode double-invoke, replay of an interrupted render), so +`setHasMore` can be scheduled twice. In practice this is benign because the value +is computed from state, but the updater is not pure, which is exactly what the +rule exists to catch. + +**Root cause:** `hasMore` is derived state. It is only used at `index.tsx:757` +(`listFooter`) and is fully determined by two values already in scope: + +```tsx +const hasMore = visibleCount < displayedProducts.length +``` + +**Confidence: high.** +**Suggested fix (removes both findings):** + +1. Delete the `hasMore` state (`:498`) and both `setHasMore` calls (`:592`, `:586`). +2. Compute `const hasMore = visibleCount < displayedProducts.length` after the + state declarations. +3. `handleShowMore` becomes `setVisibleCount((prev) => prev + 21)`, deps `[]`. + +Behaviour note: at first mount `displayedProducts` is empty, so the derived value +is `false` where the initial state was `true`. The footer is not rendered before +the catalog loads, and the effect sets the real value immediately, so nothing +visible changes. This is strictly more correct (no window where `Show More` can +show with nothing more to show). + +--- + +## 7. `rerender-memo-before-early-return` — `index.tsx:756` + +**Tool says:** the `useMemo` JSX is rebuilt on renders that take the early return. + +**Code:** `listFooter` is a `useMemo` at 756; `if (isLoading) return …` is at 776 +and the error return at 789. + +**Verdict: true positive, negligible impact.** On the loading and error renders +React still creates one small element object. There is no measurable cost, and +`--verbose` is what surfaced it. + +**Confidence: high (that it is harmless).** +**Action:** defer. It disappears naturally once the list chrome moves into a +child component (see #3, step 2). + +--- + +## 8. `rn-no-falsy-and-render` — `order-success.tsx:47` + +**Tool says (error):** when the value is `0` this renders a bare `0` and crashes +React Native. + +**Code:** + +```tsx +const totalAmount = params.totalAmount as string +... +{totalAmount && ( + Total: ₹{totalAmount} +)} +``` + +**Verdict: false positive for the crash claim.** `params` comes from +`useLocalSearchParams()`, so at runtime this is a **string** (or `undefined`), not +a number. `"0"` is truthy, so `{totalAmount && …}` renders the component — +which is the intended UI when the total is genuinely 0 — and the `0` lives inside +`` text, not as a bare child of ``. An empty string renders nothing. +The bare-`0` crash needs a numeric operand, which cannot occur here. + +**Confidence: high.** +**Optional hardening** (if you don't want to rely on the cast): +`{Boolean(totalAmount) && (…)}` — same behaviour, silences the rule. + +--- + +## 9. `rn-list-callback-per-row` — `search-results/index.tsx:98` + +**Tool says:** the `onPress` is rebuilt for every row, so memoized rows still +redraw. + +**Code:** + +```tsx +renderItem={({ item }) => ( + router.push(`/…/product-detail/${item.id}`)} + ... + /> +)} +``` + +**Verdict: true positive — and newly relevant.** `ProductCard` was just wrapped in +`React.memo` (same batch as the flash work), so this inline `onPress` is now the +one thing defeating the memo for search results: every render of the list rebuilds +the handler and re-renders every mounted card, each of which re-runs its cart/slot +hooks. + +**Confidence: high.** +**Suggested fix:** extract a memoized row: + +```tsx +const SearchResultItem = memo(({ item, itemWidth, onPress }: …) => { + const handlePress = useCallback(() => onPress(item.id), [item.id, onPress]) + return +}) +``` + +with a stable `onPress` from the screen (`useCallback` on `router`), passed as a +prop. This mirrors `FlashProductItem` in the flash page. + +--- + +## 10. `expo-lockfile` — `package.json` + +**Tool says:** multiple lock files detected (`package-lock.json`, `bun.lock`); +EAS Build infers the package manager from the lock file, so this is ambiguous. + +**Verdict: true positive, but repo-level and outside the home folder.** Confirmed +in the tree: + +- `/bun.lock` +- `/package-lock.json` +- `apps/user-ui/package-lock.json` + +**Confidence: high (the ambiguity exists); medium on which file is canonical.** +**Action:** decide which package manager is authoritative *before* deleting +anything — `package.json` scripts and CI config will show which one is actually +used. Not acted on here because it is a packaging decision, not a React fix. + +--- + +## Recommended order (if you want these fixed) + +1. **#5/#6** — derive `hasMore`, delete the impure updater. Small, contained, + removes both the error and its warning. +2. **#4a** — add the two effect dependencies. One line, correctness win. +3. **#9** — memoized search-result row. Pairs with the `ProductCard` memo already + in the tree. +4. **#2** — extract `SectionHeading`. Pure presentation, easy review. +5. **#3 / #7** — split `Dashboard` into `useHomeCatalog` + list chrome. Largest + change; do it as its own pass. +6. **#10** — lockfiles: decide, then delete. Separate change, outside React code. +7. **#1 / #4b / #8** — leave, or silence with a scoped disable and the reasoning + above. + +## Caveats + +- React Doctor is deterministic **static** analysis. It does not measure render + counts; it is not a substitute for the render probe or a production trace. +- The scan was path-scoped to this directory, but project-wide rules + (`expo-lockfile`) still fire once per project. +- `--category` only filters which findings are reported; it does not change which + files are scanned. +- Fixing #3's effect/state cluster without tests is risky — the pieces listed are + currently covered by the home test suite (`tests/pages/home.test.tsx`), so run + that suite before and after if this gets picked up. + +## Reproduce / re-check + +```bash +# same scope +cd apps/user-ui +npx react-doctor@latest --no-telemetry --blocking none --verbose \ + 'app/(drawer)/(tabs)/home' + +# only what a change introduced (after committing a base) +npx react-doctor@latest --scope changed --base main 'app/(drawer)/(tabs)/home' + +# one file +npx react-doctor@latest 'app/(drawer)/(tabs)/home/index.tsx' + +# explain one diagnostic +npx react-doctor@latest why 'app/(drawer)/(tabs)/home/index.tsx:590' +``` diff --git a/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx b/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx index a1c4cdd..66ecd4b 100755 --- a/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/home/index.tsx @@ -21,8 +21,7 @@ import MyFlatList from "common-ui/src/components/flat-list"; import { trpc } from "@/src/trpc-client"; import type { ListItemProps } from '@packages/shared'; -import { useAllProducts, useStores, useSlots, useGetEssentialConsts } from "@/src/hooks/prominent-api-hooks"; -import { useProductSlotIdentifier } from "@/hooks/useProductSlotIdentifier"; +import { useStores, useSlots, useGetEssentialConsts } from "@/src/hooks/prominent-api-hooks"; import { useCentralSlotStore } from "@/src/store/centralSlotStore"; import { useCentralProductStore } from "@/src/store/centralProductStore"; import FloatingCartBar from "@/components/floating-cart-bar"; @@ -31,6 +30,7 @@ import TabLayoutWrapper from "@/components/TabLayoutWrapper"; import LocationBar from "@/src/components/LocationBar"; import { useNavigationStore } from "@/src/store/navigationStore"; import { useHomeTagStore } from "@/src/store/homeTagStore"; +import { useHomeCatalog } from "@/hooks/useHomeCatalog"; import { HOME_INITIAL_RENDER_COUNT, HOME_MAX_RENDER_BATCH, HOME_WINDOW_SIZE } from "@/src/lib/home-list-tuning"; import NextOrderGlimpse from "@/components/NextOrderGlimpse"; dayjs.extend(relativeTime); @@ -431,6 +431,28 @@ const StoresSection = memo(({ storesData }: { storesData: any }) => { ); }); +const SectionHeading = memo(({ + title, + subtitle, + style, +}: { + title: string; + subtitle: string; + /** Outer spacing; the two callers sit in different section wrappers. */ + style?: any; +}) => ( + + + + + {title} + + {subtitle} + + +)); +SectionHeading.displayName = 'SectionHeading'; + const SlotsSection = memo(({ sortedSlots }: { sortedSlots: any[] }) => { const renderSlotItem = useCallback(({ item }: { item: any }) => ( @@ -441,15 +463,11 @@ const SlotsSection = memo(({ sortedSlots }: { sortedSlots: any[] }) => { return ( - - - - - Upcoming Delivery Slots - - Plan your fresh deliveries ahead - - + item.id.toString()} @@ -469,15 +487,11 @@ const SlotsSection = memo(({ sortedSlots }: { sortedSlots: any[] }) => { const AllProductsTitle = memo(() => ( - - - - - All Available Products - - Browse our complete selection - - + )); @@ -488,112 +502,56 @@ const EmptyCatalog = memo(() => ( )); +/** + * Rendered as an element, not memoised in Dashboard: the screen takes an early + * return for loading/error, and building this before that check is wasted work. + */ +const ShowMoreFooter = memo(({ visible, onPress }: { visible: boolean; onPress: () => void }) => { + if (!visible) return null; + + return ( + + + Show More + + + ); +}); +ShowMoreFooter.displayName = 'ShowMoreFooter'; + export default function Dashboard() { const router = useRouter(); const userDetails = useUserDetails(); const [inputQuery, setInputQuery] = useState(""); const [isLoadingDialogOpen, setIsLoadingDialogOpen] = useState(false); - const [displayedProducts, setDisplayedProducts] = useState([]); - const [visibleCount, setVisibleCount] = useState(21); - const [hasMore, setHasMore] = useState(true); - const { getQuickestSlot } = useProductSlotIdentifier(); - const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); - const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded); const refetchProducts = useCentralProductStore((state) => state.refetchProducts); const refetchSlotsFromStore = useCentralSlotStore((state) => state.refetchSlots); const [isRefreshing, setIsRefreshing] = useState(false); + // Catalogue state lives in the hook: the products payload, the per-tag rows, + // the sorted "All Products" feed and the Show More paging. const { - data: productsData, isLoading, error, - } = useAllProducts(); + products, + dashboardTags, + productsByTagId, + displayedProducts, + visibleCount, + hasMore, + showMore, + } = useHomeCatalog(); const { data: essentialConsts, error: constsError, refetch: refetchConsts } = useGetEssentialConsts(); const { data: storesData, refetch: refetchStores } = useStores(); const { data: slotsData } = useSlots(); - // Single source of truth for the catalogue: `products` and `dashboardTags` - // come out of this memo together with the per-tag rows, so the screen never - // holds two views of the same payload that can drift apart. - const { dashboardTags, products, productsByTagId } = useMemo(() => { - const dashboardTags = productsData?.tags ?? []; - const products = productsData?.products ?? []; - - // Hoisted: the old version rebuilt this Map once per tag. - const productById = new Map(); - for (const product of products) { - productById.set(product.id, product); - } - - const map: Record = {}; - for (const tag of dashboardTags) { - // Respect the admin-curated order — tag.productIds is already ordered by - // the tag's sortOrder (backend reorders it when building the cache). - // Unknown ids are skipped and a repeated id only renders once. - const ordered: any[] = []; - const seen = new Set(); - for (const id of tag.productIds || []) { - if (seen.has(id)) continue; - seen.add(id); - const product = productById.get(id); - if (product) ordered.push(product); - } - - // Out-of-stock items are pushed to the end, preserving their relative order. - const inStock: any[] = []; - const outOfStock: any[] = []; - for (const product of ordered) { - const isOut = - Boolean(productSlotsMap[product.id]?.isOutOfStock) || - (isSlotsLoaded && !getQuickestSlot(product.id)); - if (isOut) outOfStock.push(product); - else inStock.push(product); - } - map[tag.id] = [...inStock, ...outOfStock]; - } - - return { dashboardTags, products, productsByTagId: map }; - }, [productsData, productSlotsMap, isSlotsLoaded, getQuickestSlot]); - - // Tag selection/expansion live in homeTagStore (subscribed by TagTabStrip and - // TagScene), so a tap does not re-render Dashboard or rebuild the list below. - - React.useEffect(() => { - if (products.length === 0) { - setDisplayedProducts([]) - setHasMore(false) - return - } - - const allSorted = products - .filter(p => typeof p.id === "number") - .sort((a, b) => { - const slotA = getQuickestSlot(a.id) - const slotB = getQuickestSlot(b.id) - - const aOutOfStock = Boolean(productSlotsMap[a.id]?.isOutOfStock) || (isSlotsLoaded && !slotA) - const bOutOfStock = Boolean(productSlotsMap[b.id]?.isOutOfStock) || (isSlotsLoaded && !slotB) - - if (aOutOfStock && !bOutOfStock) return 1 - if (!aOutOfStock && bOutOfStock) return -1 - return 0 - }) - - setDisplayedProducts(allSorted) - setVisibleCount(21) - setHasMore(allSorted.length > 21) - }, [products, productSlotsMap]); - - const handleShowMore = useCallback(() => { - setVisibleCount((prev) => { - const next = prev + 21; - setHasMore(next < displayedProducts.length); - return next; - }); - }, [displayedProducts.length]); - const sortedSlots = useMemo(() => { if (!slotsData?.slots) return []; const now = dayjs(); @@ -753,21 +711,6 @@ export default function Dashboard() { ), [handleSearchPress, inputQuery, router, searchBarContainerStyle]); - const listFooter = useMemo(() => ( - hasMore ? ( - - - Show More - - - ) : null - ), [handleShowMore, hasMore]); - const listContentContainerStyle = useMemo(() => [ tw`pb-24`, staticStyles.flatListContent @@ -808,7 +751,7 @@ export default function Dashboard() { ListHeaderComponent={} renderSectionHeader={renderSectionHeader} renderItem={renderCatalogItem} - ListFooterComponent={listFooter} + ListFooterComponent={} refreshControl={ (value: T, delay: number): T { const { width: screenWidth } = Dimensions.get("window"); const itemWidth = (screenWidth - 48) / 2; +interface SearchResultItemProps { + item: any; + onPress: (productId: number) => void; +} + +/** + * Memoised row. The press handler is derived from the id here, so the parent's + * stable handler is the only prop that matters and `ProductCard`'s memo holds + * across list re-renders (typing, cart updates). + */ +const SearchResultItem = memo(({ item, onPress }: SearchResultItemProps) => { + const handlePress = useCallback(() => onPress(item.id), [item.id, onPress]); + + return ( + + ); +}); +SearchResultItem.displayName = "SearchResultItem"; + export default function SearchResults() { const router = useRouter(); const { q } = useLocalSearchParams(); @@ -54,7 +79,7 @@ export default function SearchResults() { const { data: productsData, isLoading, error, refetch } = useAllProducts(); - const allProducts = productsData?.products || []; + const allProducts = useMemo(() => productsData?.products ?? [], [productsData]); // Client-side search filtering using Fuse.js const products = useMemo(() => { @@ -86,22 +111,26 @@ export default function SearchResults() { // Search is now automatic via debounce, but keep this for manual submit }, []); + const handleProductPress = useCallback( + (productId: number) => { + router.push(`/(drawer)/(tabs)/home/product-detail/${productId}`); + }, + [router] + ); + + const renderProduct = useCallback( + ({ item }: { item: any }) => ( + + ), + [handleProductPress] + ); + return ( ( - - router.push(`/(drawer)/(tabs)/home/product-detail/${item.id}`) - } - showDeliveryInfo={false} - useAddToCartDialog={true} - /> - )} + renderItem={renderProduct} keyExtractor={(item) => item.id.toString()} columnWrapperStyle={{ gap: 16, justifyContent: "center" }} contentContainerStyle={[tw`pb-24`, { gap: 16 }]} diff --git a/apps/user-ui/hooks/useHomeCatalog.ts b/apps/user-ui/hooks/useHomeCatalog.ts new file mode 100644 index 0000000..5b3a245 --- /dev/null +++ b/apps/user-ui/hooks/useHomeCatalog.ts @@ -0,0 +1,119 @@ +import { useCallback, useEffect, useMemo, useState } from 'react' + +import { useProductSlotIdentifier } from '@/hooks/useProductSlotIdentifier' +import { useAllProducts } from '@/src/hooks/prominent-api-hooks' +import { useCentralSlotStore } from '@/src/store/centralSlotStore' + +/** Rows per page, same as the "Show More" step on the home catalogue. */ +export const HOME_CATALOG_PAGE_SIZE = 21 + +/** + * Home catalogue derivation: the products payload, the per-tag rows and the + * sorted "All Products" feed. + * + * This used to live inside `Dashboard`, which made that component the largest + * file in the folder and left the sort effect reading `getQuickestSlot` and + * `isSlotsLoaded` without listing them. Keeping it here leaves the screen with + * just its layout concerns, and the effect lists every value it reads. + */ +export function useHomeCatalog() { + const { data: productsData, isLoading, error } = useAllProducts() + const { getQuickestSlot } = useProductSlotIdentifier() + const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap) + const isSlotsLoaded = useCentralSlotStore((state) => state.isSlotsLoaded) + + // Single source of truth for the catalogue: `products` and `dashboardTags` + // come out of this memo together with the per-tag rows, so the screen never + // holds two views of the same payload that can drift apart. + const { dashboardTags, products, productsByTagId } = useMemo(() => { + const tags = productsData?.tags ?? [] + const allProducts = productsData?.products ?? [] + + // Hoisted: the old version rebuilt this Map once per tag. + const productById = new Map() + for (const product of allProducts) { + productById.set(product.id, product) + } + + const map: Record = {} + for (const tag of tags) { + // Respect the admin-curated order — tag.productIds is already ordered by + // the tag's sortOrder (backend reorders it when building the cache). + // Unknown ids are skipped and a repeated id only renders once. + const ordered: any[] = [] + const seen = new Set() + for (const id of tag.productIds || []) { + if (seen.has(id)) continue + seen.add(id) + const product = productById.get(id) + if (product) ordered.push(product) + } + + // Out-of-stock items are pushed to the end, preserving their relative order. + const inStock: any[] = [] + const outOfStock: any[] = [] + for (const product of ordered) { + const isOut = + Boolean(productSlotsMap[product.id]?.isOutOfStock) || + (isSlotsLoaded && !getQuickestSlot(product.id)) + if (isOut) outOfStock.push(product) + else inStock.push(product) + } + map[tag.id] = [...inStock, ...outOfStock] + } + + return { dashboardTags: tags, products: allProducts, productsByTagId: map } + }, [productsData, productSlotsMap, isSlotsLoaded, getQuickestSlot]) + + // Tag selection/expansion live in homeTagStore (subscribed by TagTabStrip and + // TagScene), so a tap does not re-render Dashboard or rebuild the list below. + const [displayedProducts, setDisplayedProducts] = useState([]) + const [visibleCount, setVisibleCount] = useState(HOME_CATALOG_PAGE_SIZE) + + useEffect(() => { + if (products.length === 0) { + setDisplayedProducts([]) + return + } + + const allSorted = products + .filter((product) => typeof product.id === 'number') + .sort((a, b) => { + const slotA = getQuickestSlot(a.id) + const slotB = getQuickestSlot(b.id) + + const aOutOfStock = + Boolean(productSlotsMap[a.id]?.isOutOfStock) || (isSlotsLoaded && !slotA) + const bOutOfStock = + Boolean(productSlotsMap[b.id]?.isOutOfStock) || (isSlotsLoaded && !slotB) + + if (aOutOfStock && !bOutOfStock) return 1 + if (!aOutOfStock && bOutOfStock) return -1 + return 0 + }) + + setDisplayedProducts(allSorted) + setVisibleCount(HOME_CATALOG_PAGE_SIZE) + }, [products, productSlotsMap, getQuickestSlot, isSlotsLoaded]) + + // Derived, not state: the old version set this from inside the setVisibleCount + // updater, which React may replay. + const hasMore = visibleCount < displayedProducts.length + + // Pure updater; the footer reads `hasMore` above. + const showMore = useCallback(() => { + setVisibleCount((prev) => prev + HOME_CATALOG_PAGE_SIZE) + }, []) + + return { + isLoading, + error, + products, + dashboardTags, + productsByTagId, + displayedProducts, + visibleCount, + hasMore, + showMore, + } +} diff --git a/change-log.txt b/change-log.txt index b34effa..600af93 100644 --- a/change-log.txt +++ b/change-log.txt @@ -488,3 +488,41 @@ visible-count reset lived in a useEffect that ran after paint. + STORE-25: an unchanged flash search query keeps the store identity. --- apps/user-ui/JEST-TEST-CASES.md ~ catalogue rows STORE-23..25 added. + +[2026-11-02 20:03:22 IST] home: fix the true-positive React Doctor findings (report in apps/user-ui/REACT-DOCTOR-HOME.md). + +--- apps/user-ui/hooks/useHomeCatalog.ts (new) ++ One hook owns the catalogue derivation that used to sit inside Dashboard: + useAllProducts + slot helpers, the products/productsByTagId memo, the + out-of-stock sort (still an effect so the reset keeps its old timing), the + displayed count and the Show More page size (21). ++ The sort effect now lists getQuickestSlot and isSlotsLoaded in its deps + (react-doctor/exhaustive-deps, index.tsx:587). Safe: getQuickestSlot is + useCallback-memoized on [slots, productSlotsMap] and the effect writes only + displayed count state, so it cannot self-trigger. ++ hasMore is derived (visibleCount < displayedProducts.length) instead of state, + and showMore is a pure updater, removing the nested setHasMore() call inside + setVisibleCount (react-doctor/no-impure-state-updater, + no-side-effect-in-state-updater-function). +--- apps/user-ui/app/(drawer)/(tabs)/home/index.tsx +~ Dashboard calls useHomeCatalog(); the catalogue memo, sort effect, both + catalogue states and handleShowMore moved out (~75 lines). Behaviour, testIDs + and the HOME_* virtualization props unchanged. +~ New SectionHeading component shared by SlotsSection and AllProductsTitle, + which repeated the same 9-line heading (duplicate-jsx-subtree). +--- apps/user-ui/app/(drawer)/(tabs)/home/search-results/index.tsx +~ New memoized SearchResultItem owns its onPress (derived from item.id) and the + screen passes a stable handleProductPress, so the inline handler no longer + defeats ProductCard's memo (rn-list-callback-per-row). +- Left as-is, with reasons in the report: the tag strip is a ScrollView on + purpose (rn-no-scrollview-mapped-list), totalAmount is a string from + useLocalSearchParams (rn-no-falsy-and-render), root lock files need a + package-manager decision (expo-lockfile). +~ ShowMoreFooter is now a memo component rendered as ListFooterComponent, + instead of a useMemo built before the loading/error early returns + (rerender-memo-before-early-return). +~ search-results: allProducts is memoised on productsData so the Fuse memo has a + stable dependency (react-hooks/exhaustive-deps). +- Re-scan after the fixes: 11 -> 3 findings. The 3 left are the documented false + positives (tag-strip ScrollView, string totalAmount) and the root lockfile + decision.