Files
vercel/examples/hydrogen-2/app/utils.ts
Nathan Rajlich 97659c687b [examples] Add "hydrogen-2" template (#10319)
Adds a Hydrogen v2 template which is the output of the `npm create @shopify/hydrogen@latest` command.

Note that a `vercel.json` file is being used to define the environment variables that are required at runtime. This is required for the template to deploy with zero configuration, however the user should update these values (including replacing the session secret) and migrate them to the Project settings in the Vercel dashboard.

[Live example](https://hydrogen-v2-template.vercel.app)
2023-08-10 00:11:33 +00:00

47 lines
1.1 KiB
TypeScript

import {useLocation} from '@remix-run/react';
import type {SelectedOption} from '@shopify/hydrogen/storefront-api-types';
import {useMemo} from 'react';
export function useVariantUrl(
handle: string,
selectedOptions: SelectedOption[],
) {
const {pathname} = useLocation();
return useMemo(() => {
return getVariantUrl({
handle,
pathname,
searchParams: new URLSearchParams(),
selectedOptions,
});
}, [handle, selectedOptions, pathname]);
}
export function getVariantUrl({
handle,
pathname,
searchParams,
selectedOptions,
}: {
handle: string;
pathname: string;
searchParams: URLSearchParams;
selectedOptions: SelectedOption[];
}) {
const match = /(\/[a-zA-Z]{2}-[a-zA-Z]{2}\/)/g.exec(pathname);
const isLocalePathname = match && match.length > 0;
const path = isLocalePathname
? `${match![0]}products/${handle}`
: `/products/${handle}`;
selectedOptions.forEach((option) => {
searchParams.set(option.name, option.value);
});
const searchString = searchParams.toString();
return path + (searchString ? '?' + searchParams.toString() : '');
}