Skip to content

Commit

Permalink
fix: ensure products returned by useproductsbyids is in right order
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremyagabriel committed Dec 27, 2024
1 parent 2a22176 commit 2416059
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions app/hooks/product/useProductsByIds.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useEffect} from 'react';
import {useEffect, useMemo} from 'react';
import {useFetcher} from '@remix-run/react';
import type {Product} from '@shopify/hydrogen/storefront-api-types';

Expand All @@ -24,6 +24,8 @@ export function useProductsByIds(
key: `products-from-handles:${ids.join(',')}:${pathPrefix}`,
});

const idsString = JSON.stringify(ids);

useEffect(() => {
if (!fetchOnMount || !ids?.length || fetcher.data?.products) return;
const searchParams = new URLSearchParams({
Expand All @@ -36,7 +38,21 @@ export function useProductsByIds(
count: ids.length.toString(),
});
fetcher.load(`${pathPrefix}/api/products?${searchParams}`);
}, [fetchOnMount, JSON.stringify(ids)]);
}, [fetchOnMount, idsString]);

return fetcher.data?.products?.filter(Boolean) || [];
return useMemo(() => {
if (!ids?.length || !fetcher.data?.products) return [];
const productsById = fetcher.data.products.reduce(
(acc: Record<string, Product>, product) => {
if (!product) return acc;
return {...acc, [product.id]: product};
},
{},
);
// Ensure products are returned in the same order as the ids
return ids.reduce((acc: Product[], id) => {
if (!productsById[id]) return acc;
return [...acc, productsById[id]];
}, []);
}, [fetcher.data?.products, idsString]);
}

0 comments on commit 2416059

Please sign in to comment.