Skip to content

Commit

Permalink
Cleanup getSelectedProductOptions implementation and add JSDocs (#2089
Browse files Browse the repository at this point in the history
)

* Cleanup getSelectedProduct options implmentation

* Add JSDocs to getSelectedProductOptions

* Add changeset
  • Loading branch information
juanpprieto committed May 8, 2024
1 parent cc9b548 commit 6f5061d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 14 deletions.
6 changes: 6 additions & 0 deletions .changeset/orange-snakes-shout.md
@@ -0,0 +1,6 @@
---
'skeleton': patch
'@shopify/hydrogen': patch
---

Add JSdoc to `getSelectedProductOptions` utility and cleanup the skeleton implementation
20 changes: 20 additions & 0 deletions packages/hydrogen/src/product/VariantSelector.ts
Expand Up @@ -133,6 +133,26 @@ export function VariantSelector({

type GetSelectedProductOptions = (request: Request) => SelectedOptionInput[];

/**
* Extract searchParams from a Request instance and return an array of selected options.
* @param request - The Request instance to extract searchParams from.
* @returns An array of selected options.
* @example Basic usage:
* ```tsx
*
* import {getSelectedProductOptions} from '@shopify/hydrogen';
*
* // Given a request url of `/products/product-handle?color=red&size=large`
*
* const selectedOptions = getSelectedProductOptions(request);
*
* // selectedOptions will equal:
* // [
* // {name: 'color', value: 'red'},
* // {name: 'size', value: 'large'}
* // ]
* ```
**/
export const getSelectedProductOptions: GetSelectedProductOptions = (
request,
) => {
Expand Down
16 changes: 2 additions & 14 deletions templates/skeleton/app/routes/products.$handle.tsx
Expand Up @@ -26,33 +26,21 @@ import type {
} from '@shopify/hydrogen/storefront-api-types';
import {getVariantUrl} from '~/lib/variants';

export const meta: MetaFunction<typeof loader> = ({data, location}) => {
export const meta: MetaFunction<typeof loader> = ({data}) => {
return [{title: `Hydrogen | ${data?.product.title ?? ''}`}];
};

export async function loader({params, request, context}: LoaderFunctionArgs) {
const {handle} = params;
const {storefront} = context;

const selectedOptions = getSelectedProductOptions(request).filter(
(option) =>
// Filter out Shopify predictive search query params
!option.name.startsWith('_sid') &&
!option.name.startsWith('_pos') &&
!option.name.startsWith('_psq') &&
!option.name.startsWith('_ss') &&
!option.name.startsWith('_v') &&
// Filter out third party tracking params
!option.name.startsWith('fbclid'),
);

if (!handle) {
throw new Error('Expected product handle to be defined');
}

// await the query for the critical product data
const {product} = await storefront.query(PRODUCT_QUERY, {
variables: {handle, selectedOptions},
variables: {handle, selectedOptions: getSelectedProductOptions(request)},
});

if (!product?.id) {
Expand Down

0 comments on commit 6f5061d

Please sign in to comment.