How to implement BuyNowButton in Hydrogen v2? #559
-
Hi, I'm wondering what's the correct way to implement the BuyNowButton in Hydrogen v2? At the moment I've got it kinda working. What I've done is:
Issues
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
did you fix the issue |
Beta Was this translation helpful? Give feedback.
-
The The bases of buy now button is that it creates a new cart with cart lines and redirects you to checkout once that is done. So, to implement this behaviour in H2, we just need to do exactly that. We just recently release a new cart abstraction that helps with tasks like this. it is currently available on the With that set of instructions, you can set up an add to cart button that can behave like a buy now button. simply pass a form data to the cart action to tell it to redirect. For example, after step 4 from the instruction: Step 5 - Create a BuyNowButtonimport {CartForm} from '@shopify/hydrogen';
export default function BuyNowButton({lines}) {
return (
<CartForm
route="/cart"
action={CartForm.ACTIONS.LinesAdd}
inputs={
{lines}
}
>
<input type="hidden" name="redirectToCheckout" value="true" />
<button>
Add to cart
</button>
</CartForm>
);
} Step 6: Handle checkout redirectimport {CartForm} from '@shopify/hydrogen';
import invariant from 'tiny-invariant';
export async function action({request, context}) {
const {cart} = context;
const formData = await request.formData();
const {action, inputs} = CartForm.getFormInput(formData);
...
// The Cart ID might change after each mutation, so update it each time.
const headers = cart.setCartId(result.cart.id);
// Handle redirect
if (inputs.redirectToCheckout === 'true' ) {
headers.append('Location:', result.cart.checkoutUrl)
}
return json(
result,
{status: inputs.redirectToCheckout === 'true' ? 301 : 200, headers},
); |
Beta Was this translation helpful? Give feedback.
There's a couple mistakes in my code example:
Couple things to make sure:
1. In
server.ts
, make sure to override thecartMutateFragment
so that it returns a checkout url. (In hindsight, we probably should make this a default field to return)2. When adding a Buy now button, you…