Shopify / checkout-sheet-kit-react-native

Shopify's Checkout Sheet Kit for React Native - simplifying the process of adding checkout to your native apps.
https://shopify.dev/docs/custom-storefronts/mobile-apps
MIT License
30 stars 3 forks source link

Add support for Checkout events, add ShopifyCheckoutKitProvider context #20

Closed markmur closed 9 months ago

markmur commented 9 months ago

What are you trying to accomplish?

Programmatic usage

Note: each of the addEventListener calls will return an EmitterSubscription object containing a remove() function to remove the listener.

import {ColorScheme, ShopifyCheckoutKit} from 'react-native-shopify-checkout-kit'

const shopify = new ShopifyCheckoutKit({
  colorScheme: ColorScheme.automatic,
  preloading: true,
})

// Events: 'close', 'completed', 'error'
shopify.addEventListener('close', () => {
    // Do something on close
})

shopify.addEventListener('completed', () => {
    // Do something on checkout completion
})

shopify.addEventListener('error', (error) => {
    // Do something on checkout error
   // console.log(error.message)
})

[Recommended] Context usage

import {ColorScheme, ShopifyCheckoutKitProvider, useShopifyCheckoutKit} from 'react-native-shopify-checkout-kit'

function App() {
  const shopifyCheckout = useShopifyCheckoutKit()

  const  handleCheckout = useCallback(() => {
     // Open checkout
    shopifyCheckout.present(checkoutUrl)
  }, [])

  // Subscribe to checkout events
  useEffect(() => {
     const subscription = shopifyCheckout.addEventListener('completed', () => {
        // clear cart
     })

     return () => subscription?.remove()
  }, [shopifyCheckout])

  return (
     <Button title="Checkout" onPress={handleCheckout} />
  )
}

function AppWithContext() {
  return (
    <ShopifyCheckoutKitProvider 
        configuration={{
          colorScheme: ColorScheme.automatic,
          preloading: true
        }}>
       <App />
    </ShopifyCheckoutKitProvider>
  )
}