Untitled

 avatar
unknown
javascript
a year ago
2.9 kB
8
Indexable
import {
  BlockStack,
  Choice,
  reactExtension,
  ChoiceList,
  useSettings,
  useAttributes,
  useApplyAttributeChange
} from '@shopify/ui-extensions-react/checkout';
import { useState } from 'react';

export default reactExtension('purchase.checkout.contact.render-after', () => <Extension />);

function Extension() {
  const { direct_mail_label: directMailFormLabel, third_party_label: thirdPartyFormLabel } =
    useSettings();
  const applyAttributesChange = useApplyAttributeChange();

  /**
   * Get the checkbox labels and set defaults
   */
  const directMailLabel = directMailFormLabel ?? 'Direct Mail';
  const thirdPartyLabel = thirdPartyFormLabel ?? '3rd Party';

  /**
   * Set the default state for the checkboxes
   */
  const [directMailChecked, setDirectMailChecked] = useState(false);
  const [thirdPartyChecked, setThirdPartyChecked] = useState(false);

  /**
   * Handle when direct mail is clicked
   * @param {string} value
   */
  async function handleDirectMailChange(value) {
    const isChecked = value.length === 1;

    /**
     * Update the order attribute for direct_mail
     */
    const result = await applyAttributesChange({
      type: 'updateAttribute',
      key: 'direct_mail',
      value: isChecked ? 'true' : 'false'
    });

    /**
     * If attribute is added, updat the checkbox state
     */
    if (result.type === 'success') {
      setDirectMailChecked(isChecked);
    }
  }

  /**
   * Handle when third party is clicked
   * @param {string} value
   */
  async function handleThirdPartyChange(value) {
    const isChecked = value.length === 1;

    /**
     * Update the order attribute for third_party
     */
    const result = await applyAttributesChange({
      type: 'updateAttribute',
      key: 'third_party',
      value: isChecked ? 'true' : 'false'
    });

    /**
     * If attribute is added, updat the checkbox state
     */
    if (result.type === 'success') {
      setThirdPartyChecked(isChecked);
    }
  }

  const directMailSelected = [];
  const thirdPartySelected = [];

  if (directMailChecked) {
    directMailSelected.push('direct_mail');
  }

  if (thirdPartyChecked) {
    thirdPartySelected.push('third_party');
  }

  return (
    <BlockStack>
      <ChoiceList
        name="consentDirectMail"
        value={directMailSelected}
        onChange={handleDirectMailChange}>
        <BlockStack>
          <Choice id="direct_mail" accessibilityLabel={directMailLabel}>
            {directMailLabel}
          </Choice>
        </BlockStack>
      </ChoiceList>

      <ChoiceList
        name="consentThirdParty"
        value={thirdPartySelected}
        onChange={handleThirdPartyChange}>
        <BlockStack>
          <Choice id="third_party" accessibilityLabel={thirdPartyLabel}>
            {thirdPartyLabel}
          </Choice>
        </BlockStack>
      </ChoiceList>
    </BlockStack>
  );
}
Editor is loading...
Leave a Comment