Announcing React Native IAP hooks

Hyo
dooboolab
Published in
2 min readFeb 13, 2021

React Native IAP is now 3 years old now. Finally the hook has arrived.

Status in Feb, 14th, 2021

Today, I brought better purchase flow to handle in React Native. From react-native-iap@6.0.0+ , we have useIAP hook that handles purchases better. I’ll go over step by step on how to use it.

1. Installation

Installation is recommended above react-native-iap@6.0.0-rc.15. For early adopters, you can install it with next package of module.

yarn add react-native-iap@next

2. Import

After that, you can import useIAP hook.

import {requestPurchase, requestSubscription, useIAP} from 'react-native-iap';

3. Fetch products

If you’ve completed creating purchase products like in the post, let's get them using useIAP hook.

Previously, our code looked like below.

You needed to call getProducts in useEffect imperatively and should add listeners when initConnection is successful. With useIAP hook, these are handled automatically. You do not have to call initConnection imperatively and calling useIAP() is enough for that.

const {
connected,
products,
subscriptions,
getProducts,
getSubscriptions,
finishTransaction,
currentPurchase,
currentPurchaseError,
} = useIAP();

The connected variable tells you whether native IAP module is able to interact with react codes.

When you call getProducts or getSubscriptions, the products or the subscriptions will be fetched and it will update products and subscriptions variables.

4. Purchase products

Now you are ready to purchase products since products are fetched. Now it is time to look at currentPurchase and currentPurchaseError variables in useIAP(). With previous functions in react-native-iap, which are requestPurchase and requestSubscription, you can request purchases.

const purchase = (item: Purchase): void => {
if (item.type === 'iap') requestPurchase(item.productId);
else requestSubscription(item.productId);
};

When they are called successfully, currentPurchase and currentPurchaseError will be updated. You can handle those purchases like below.

useEffect(() => {
getProducts(iapSkus);
getSubscriptions(subSkus);
}, [getProducts, getSubscriptions]);
useEffect(() => {
const checkCurrentPurchase = async (purchase?: Purchase): Promise<void> => {
if (purchase) {
const receipt = purchase.transactionReceipt;
if (receipt)
try {
const ackResult = await finishTransaction(purchase);
console.log('ackResult', ackResult);
} catch (ackErr) {
console.warn('ackErr', ackErr);
}
}
};
checkCurrentPurchase(currentPurchase);
}, [currentPurchase, finishTransaction]);

Final result

Fetch products then purchase demo

Finally, we have useIAP hook integrated. Currently, this is still in beta and will be released soon.

Thanks for all for enjoying react-native-iap 🙏.

--

--