What I want to achieve is to redirect or show a view upon successful purchase. Purchase is successful but the state variable is not updating inside validateReceiptIos handler.
I checked the validation of the receipt but after that not even able to redirect to another page or load a view on the condition. I am attaching a code snippet below.
const productIds = ['xxx_xx_xx'];
const InAppPurchase = ({ navigation }) => {
const [products, setProducts] = useState([]);
const [purchased, setPurchased] = useState(false);
const [email, setEmail] = useState({
emailText: '',
emailValidity: false,
emailErrorText: null,
});
const [name, setName] = useState({
nameText: '',
nameValidity: false,
nameErrorText: null,
});
const validateUserName = (text) => {
if (text.length < 1) {
setName({ nameText: text, nameValidity: false, nameErrorText: 'Name cannot be empty' });
}
else { setName({ nameText: text, nameValidity: true, nameErrorText: '' }); }
};
const validateEmail = (text) => {
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(text) === false && text.length > 0) {
setEmail({ emailText: text, emailValidity: false, emailErrorText: 'Invalid email' });
} else if (text.length < 1) {
setEmail({ emailText: text, emailValidity: false, emailErrorText: 'Email cannot be empty' });
}
else { setEmail({ emailText: text, emailValidity: true, emailErrorText: '' }); }
};
const validate = async (receipt, purchase) => {
const receiptBody = {
"receipt-data": receipt,
"password": "xxxxxxxxxxxxxxxxxxxxxx"
}
const result = await IAP.validateReceiptIos(receiptBody, true).catch(() => {
}).then((receipt) => {
try {
const renewalHistory = receipt.latest_receipt_info;
const expiration = renewalHistory[renewalHistory.length - 1].expires_date_ms;
// const expiration = renewalHistory[0].expires_date_ms;
let expired = Date.now() > expiration;
if (!expired) {
IAP.finishTransaction(purchase);
setPurchased(true); //***Not updating the state variable***
//navigation.navigate('Success') //***Not even navigate to another page***
} else {
Alert.alert("Purchase expired", "Your subscription has been expired, please resubscribe to continue using the app")
}
} catch (error) {
console.log(error)
}
})
}
useEffect(() => {
IAP.getProducts(productIds).then(res => {
setProducts(res);
})
const purchaseUpdateSubscription = IAP.purchaseUpdatedListener(purchase => {
const receipt = purchase.transactionReceipt;
if (receipt) {
validate(receipt, purchase)
}
})
return () => {
purchaseUpdateSubscription.remove();
}
}, []);
if (purchased) {
return (
<SafeAreaView style={styles.container}>
<View style={styles.containerInner}>
<View style={{ flex: 1, flexDirection: "column" }}>
<View style={styles.logoSuccessSection}>
<Image style={styles.successLogo} source={require('../images/success.png')} />
</View>
<View style={{ flex: 1 }}>
<TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Login')}>
<Text style={styles.signText}>CONTINUE</Text>
</TouchableOpacity>
</View>
</View>
</View>
</SafeAreaView>
)
} else {
return (
<SafeAreaView style={styles.container}>
<View style={styles.containerInner}>
<View style={styles.logoSection}>
<Image style={styles.logo} source={require('../images/logo.jpg')} />
</View>
<View style={styles.headerContainer}>
<Text style={styles.headerText}>PREMIUM ACCESS</Text>
</View>
<View style={styles.featureContainer}>
<ScrollView style={{ flexDirection: 'column', paddingVertical: 20 }}>
<TextInput blurOnSubmit={true} autoCapitalize='none' placeholderTextColor="#736c6c"
style={{ height: 40, borderColor: '#d6d8e1', borderWidth: 1, paddingHorizontal: 10 }} placeholder="Email" onChangeText={(text) => validateEmail(text)} onSubmitEditing={(event) => setEmail({ emailText: event.nativeEvent.text })}
/>
{email.emailValidity === false ? <Text style={styles.errorTextStyle}>{email.emailErrorText}</Text> : null}
<TextInput blurOnSubmit={true} autoCapitalize='none' placeholderTextColor="#736c6c"
style={{ height: 40, borderColor: '#d6d8e1', borderWidth: 1, paddingHorizontal: 10, marginVertical: 5 }} placeholder="Name" onChangeText={(text) => validateUserName(text)} onSubmitEditing={(event) => setName({ nameText: event.nativeEvent.text })}
/>
{name.nameValidity === false ? <Text style={styles.errorTextStyle}>{name.nameErrorText}</Text> : null}
</ScrollView>
</View>
<View>
{products.map((product, i) =>
<TouchableOpacity key={i} style={styles.button} onPress={() => {
if (email.emailValidity === false || name.nameValidity === false) {
Alert.alert(
"Email & Name fields cannot be empty.",
"",
[
{ text: "OK", onPress: () => console.log("OK Pressed") }
],
{ cancelable: false }
);
} else {
IAP.requestSubscription(product.productId);
}
}}>
<Text style={styles.signText}>SUBSCRIBE - $9.99/Month</Text>
</TouchableOpacity>
)}
</View>
</View>
</SafeAreaView>
)
}
}