hydrogen
hydrogen copied to clipboard
[BUG] Wrong initial product variants
Describe the bug
Hydrogen doesn't seem to provide a default mechanism for keeping track of the correct variant.
This is basically a duplicate of Shopify/hydrogen#538 and I agree with all of the comments from that issue.
I'm not sure why that issue was closed, there's no reference to an actual fix and this is still not working out of the box or on the demo store.
Is there any advantage to doing this for each option (ie. ?size=
) instead of the variant (ie. ?variant=
)?
It seems like just tracking the variant in the URL is easier, more inline with existing storefronts and compatible with ProductOptionsProvider
.
To Reproduce
https://www.hydrogen.shop/products/snowboard?size=158&binding%2520mount=rsc&material=polycarbonate
- Load the demo store using the above link
- Notice the selected options in the fields don't match the selected options in the URL
Expected behaviour
Hydrogen should maintain state for the correct variant across routes and it should be possible to link directly to the correct variant.
Additional context
- Hydrogen version
1.6.0
- Node version
16.18.0
- Device details
iMac (macOS Monterey 12.4)
This is one of the areas that should work better in Hydrogen v2, given the recent announcement https://remix.run/blog/remixing-shopify and the work that we're doing there.
Interesting, I hadn't seen that announcement, thanks for sharing.
Do you know if there's any plans to address this prior to version 2?
Prior to v2 I think is unlikely. However, there's now also the hydrogen-ui project where the source code for ProductOptionsProvider will now live. So it's hard to say whether the solution for this will exist in hydrogen v2 or in hydrogen-ui. My initial impression was that having it tied to the url means it's more likely in hydrogen, but we also want to improve ProductProvider in hydrogen-ui too.
I agree, it needs to be reflected in the URL for a bunch of reasons, which seems more related to the framework.
Is this at least worth resolving in the demo for now?
ProductOptionsProvider
already supports initialVariantId
, so does this just need to be synced with selectedVariant
through the URL?
const { pathname } = useUrl()
const { selectedVariant } = useProductOptions();
useEffect(() => {
window.history.replaceState(
null,
'',
`${pathname}?variant=${selectedVariant?.id?.replace('gid://shopify/ProductVariant/', '')}`,
);
}, [pathname, selectedVariant])
const { search } = useUrl();
let selectedVariant = undefined
if (search) {
const params = new URLSearchParams(search)
if (params.has('variant')) {
selectedVariant = `gid://shopify/ProductVariant/${params.get('variant')}`
}
}
<ProductOptionsProvider initialVariantId={selectedVariant}>