Shopify / ui-extensions

MIT License
248 stars 35 forks source link

useApplyAttributeChange() performance issue #2057

Open ebatarson-axome opened 3 weeks ago

ebatarson-axome commented 3 weeks ago

Version : "@shopify/ui-extensions": "2024.4.x", "@shopify/ui-extensions-react": "2024.4.x"

Describe the bug

Hello, I'm having a problem with a checkout V2 extension for which I'm using the useApplyAttributeChange() hook. This hook generates multiple renderings of my component. I go from a few renderings to dozens or even hundreds. Would it be possible to launch the update of multiple control attributes (instead of having to do them one by one)?

Steps to reproduce the behavior:

const applyAttributeChange = useApplyAttributeChange();
const saveMyAttributes = async () => {
  const result =
      await applyAttributeChange({
        type: 'updateAttribute',
        key: myAttribute1,
        value: value1,
      })
      &&
      await applyAttributeChange({
        type: 'updateAttribute',
        key: myAttribute2,
        value: value2,
      })
      && await applyAttributeChange({
        type: 'updateAttribute',
        key: myAttribute3,
        value: value3
      })
      && await applyAttributeChange({
        type: 'updateAttribute',
        key: myAttribute4,
        value: value4
      })
      && await applyAttributeChange({
        type: 'updateAttribute',
        key: myAttribute5,
        value: value5
      })

    // Update ok ? 
    if (result.type === 'success') {
     // Do stuff...
    }
}
useEffect(() => {

    const toUpdate = MY_CONDITION_TO_UPDATE_CODE
    if (toUpdate) {
      saveMyAttributes()
    }
  }, []);

This code isn't called on every reload, but via a useEffect to keep component updates to a minimum.

Expected behavior

Multiple updates on several control attributes at the same time

hashemHP commented 2 weeks ago

i had same scenario just ran all the updates at once without await and it seemed to be working fine for my case all attributes get applied at same time

ebatarson-axome commented 2 weeks ago

Wahooo! What a difference! Indeed, it generates far, far fewer renderings! Thanks a lot @hashemHP

ebatarson-axome commented 2 weeks ago

Nevertheless, in the hook's documentation, we're supposed to obtain a promise (https://shopify.dev/docs/api/checkout-ui-extensions/2024-04/apis/attributes#useApplyAttributeChange), which means we have to process it asynchronously. So async/await operation seemed logical. What happens tomorrow if Shopify's handling of this hook changes? I'm wondering about the maintainability of my app...