Re: How to get the selected shipping/delivery method in checkout ui extensions

Solved

How to get the selected shipping/delivery method in checkout ui extensions

a_zelinsky
Shopify Partner
24 0 4

I have a text field checkout ui extension that I'm looking to modify. I'm wondering how to utilize the deliveryGroups API to get the selected shipping method. This is my current code for my extension. Any help here would be greatly appreciated!

 

import React, { useState, useEffect } from 'react';
import {
  useExtensionApi,
  render,
  TextField,
  useApplyAttributeChange,
} from '@shopify/checkout-ui-extensions-react';

render("Checkout::ShippingMethods::RenderAfter", () => <App />);

function App() {
  const { extensionPoint } = useExtensionApi();
  const [shippingAccountInfo, setShippingAccountInfo] = useState('');

  const handleShippingChange = (val) => {
    setShippingAccountInfo(val)
  }

  const applyAttributeChange = useApplyAttributeChange();

  useEffect(() => {
    if (shippingAccountInfo) {
      // Update the checkout line item with the VAT number attribute
      async function updateShippingAttribute() {
        let res = await applyAttributeChange({
          type: 'updateAttribute',
          key: 'shipping_info',
          value: shippingAccountInfo,
        });
      }

      updateShippingAttribute()
    }
  }, [shippingAccountInfo, applyAttributeChange]);


  return (
    <>
      <TextField
        label="Shipping Account Info: (Enter your carrier and account number)"
        name="shipping_account_info"
        value={shippingAccountInfo}
        onChange={(str) => handleShippingChange(str)}
      />
    </>
  );
}
Accepted Solution (1)
vixnguyen
Shopify Partner
45 4 5

This is an accepted solution.

Hi A_zelinsky,

In your case, you can use useSubscription with useExtensionApi to watch changes. It's working as your expectation. Please try!

const { deliveryGroups } = useExtensionApi();

const _deliveryGroups = useSubscription(deliveryGroups);

useEffect(() => {

     // do something here

}, [_deliveryGroups]);

Regards,

View solution in original post

Replies 12 (12)

vixnguyen
Shopify Partner
45 4 5

Hi @a_zelinsky ,

You can retrive deliveryGroup by using Storefront API Access.

Hope it helps

a_zelinsky
Shopify Partner
24 0 4

Hi! Thank you so much for your reply. Are you able to provide a code snippet of how you would get the deliveryGroups object from the Storefront API?

vixnguyen
Shopify Partner
45 4 5

Hi,

Simpler, you can use useExtensionApi to access deliveryGroups

Code snippet:

const { deliveryGroups } = useExtensionApi();

Regards,

a_zelinsky
Shopify Partner
24 0 4

Hi Vix,

Thanks again for your help, it is really appreciated. I changed my code to incorporate your code snippet. However, I'm having difficulty listening to changes to the customer's chosen delivery method. I'm hoping you could provide any insight on how we could listen to changes on the delivery method, so I can update the state accordingly. I'm assuming it's not running the useEffect due to the reference value not changing on the deliveryGroups object.


Thank you so much for your help!

 

 

import React, { useState, useEffect } from 'react';
import {
  useExtensionApi,
  render,
  TextField,
  useApplyAttributeChange,
} from '@shopify/checkout-ui-extensions-react';

render('Checkout::Dynamic::Render', () => <App />);

function App() {
  const { deliveryGroups } = useExtensionApi();
  const [shippingAccountInfo, setShippingAccountInfo] = useState('');
  const [selectedDeliveryOption, setSelectedDeliveryOption] = useState(null);

  useEffect(() => {
    // Check if deliveryGroups and deliveryGroups.current are defined, and if deliveryGroups.current has at least one item
    if (deliveryGroups && deliveryGroups.current && deliveryGroups.current.length > 0) {
      // Extract the handle of the selectedDeliveryOption from the first item in the current array
      const handle = deliveryGroups.current[0].selectedDeliveryOption.handle;
      setSelectedDeliveryOption(handle);
    }
  }, [deliveryGroups]);

  console.log('deliveryGroups', deliveryGroups)
  console.log('selectedDeliveryOption', selectedDeliveryOption)

  const handleShippingChange = (val) => {
    setShippingAccountInfo(val)
  }

  const applyAttributeChange = useApplyAttributeChange();

  useEffect(() => {
    if (shippingAccountInfo) {
      // Update the checkout line item with the VAT number attribute
      async function updateShippingAttribute() {
        let res = await applyAttributeChange({
          type: 'updateAttribute',
          key: 'shipping_info',
          value: shippingAccountInfo,
        });
      }

      updateShippingAttribute()
    }
  }, [shippingAccountInfo, applyAttributeChange]);


  return (
    <>
      <TextField
        label="Shipping Account Info: (Enter your carrier and account number)"
        name="shipping_account_info"
        value={shippingAccountInfo}
        onChange={(str) => handleShippingChange(str)}
      />
    </>
  );
}

 

 



 

vixnguyen
Shopify Partner
45 4 5

Hi,

The useEffect is not fire because of 2 main points:

- The extension points

- The object you are watching

It's currently the issue of Checkout UI extension is not stable for now.

In your case, you can watch deliveryGroups by place the extension in the right place, watch changes in the right step.

For Checkout UI extension, it's depended on particular use cases, so I can not help you to solve your problem.

But one important thing, could you share me the business requirement, I can advice you to use other techniques.

Regards,

vixnguyen
Shopify Partner
45 4 5

This is an accepted solution.

Hi A_zelinsky,

In your case, you can use useSubscription with useExtensionApi to watch changes. It's working as your expectation. Please try!

const { deliveryGroups } = useExtensionApi();

const _deliveryGroups = useSubscription(deliveryGroups);

useEffect(() => {

     // do something here

}, [_deliveryGroups]);

Regards,

a_zelinsky
Shopify Partner
24 0 4

Thank you Vixnguyen, this worked exactly as I needed it to. I really appreciate your willingness to help!

ZeeshanSigma
Shopify Partner
5 0 0

Hi @vixnguyen ,
i want to show the text field when shipping method (having customer account in their title) is selected. Currently it shows the field also i didn't get the current selected method.
`

import React, { useState, useEffect } from 'react';
import {
useExtensionApi,
render,
TextField,
useApplyAttributeChange,
useSubscription,
} from '@shopify/checkout-ui-extensions-react';

render('Checkout::ShippingMethods::RenderAfter', () => <App />);

function App() {
const { deliveryGroups } = useExtensionApi();
const [shippingAccountInfo, setShippingAccountInfo] = useState('');
const [selectedDeliveryOption, setSelectedDeliveryOption] = useState(null);
const applyAttributeChange = useApplyAttributeChange();

// Listen for changes on the selected shipping method using useSubscription
const _deliveryGroups = useSubscription(deliveryGroups);

useEffect(() => {
// Check if deliveryGroups and deliveryGroups.current are defined, and if deliveryGroups.current has at least one item
if (_deliveryGroups && _deliveryGroups.current && _deliveryGroups.current.length > 0) {
// Extract the handle of the selectedDeliveryOption from the first item in the current array
const handle = _deliveryGroups.current[0].selectedDeliveryOption.handle;
setSelectedDeliveryOption(handle);
}
}, [_deliveryGroups]);

const handleShippingChange = (val) => {
setShippingAccountInfo(val);
}

useEffect(() => {
if (shippingAccountInfo) {
// Update the checkout line item with the shipping_info attribute
async function updateShippingAttribute() {
let res = await applyAttributeChange({
type: 'updateAttribute',
key: 'shipping_info',
value: shippingAccountInfo,
});
}

updateShippingAttribute();
}
}, [shippingAccountInfo, applyAttributeChange]);

return (
<>
<TextField
label="Shipping Account Info: (Enter your carrier and account number)"
name="shipping_account_info"
value={shippingAccountInfo}
onChange={(str) => handleShippingChange(str)}
/>
</>
);
}


`

vixnguyen
Shopify Partner
45 4 5

Hi,

Could you please let me know exactly what is your issue? And what do you want to solve. So that I can help.

Regards,

vikasanjana
Shopify Partner
5 0 1

@vixnguyen 
Hello hope you are doing well i have one more question add on it can we apply any delivery option using checkout ui extension i actually i am creating a delivery customization function that hide a one time purchase deviery at certain condition but when hiding it blocks us to checkout and showing 

vixnguyen
Shopify Partner
45 4 5

Hi,

In your case, I think the delivery customization function is the right solution to solve the problem, I don't know exactly what is the root cause that blocks customer to checkout, but it's required to have one delivery option available at checkout step. You might need to add more delivery option to your store.

Cedcommerce
Shopify Partner
718 76 113

Hello @a_zelinsky,

We must check the store code to help you with the desired solution. Please help us with your Shopify store URL and other information so we can check the same.

Regards,
CedCommerce

CedCommerce || Shopify Expert
- Let us know if our reply is helpful for you. Like it.
- Was your question answered? Mark it as an accepted solution.
- For further discussion contact: Email ID- [email protected]
- Whatsapp:- Join Here