Skip to content

Instantly share code, notes, and snippets.

@rennard
Created October 31, 2024 19:44
Show Gist options
  • Select an option

  • Save rennard/8b38d7e3ff23207b872b1d223552c694 to your computer and use it in GitHub Desktop.

Select an option

Save rennard/8b38d7e3ff23207b872b1d223552c694 to your computer and use it in GitHub Desktop.
A listener to keep track of adapty payments status
import React, {
useCallback,
createContext,
FC,
PropsWithChildren,
useEffect,
useState
} from 'react';
import { adapty, AdaptyProfile, AdaptySubscription } from 'react-native-adapty';
export interface ProfileContextProps {
paymentProfile: AdaptyProfile | null;
hasPremiumAccess: boolean;
activeSubscription: AdaptySubscription | null;
inTrial: boolean;
refetch: () => void;
willRenew: boolean;
}
export const ProfileContext = createContext<ProfileContextProps | undefined>(
undefined
);
const isEmpty = (val: any) => Object.entries(val).length === 0;
const ProfileProvider: FC<PropsWithChildren> = ({ children }) => {
const [paymentProfile, setPaymentProfile] = useState<AdaptyProfile | null>(
null
);
const [hasPremiumAccess, setHasPremiumAccess] = useState<boolean>(false);
const [activeSubscription, setActiveSubscription] =
useState<AdaptySubscription | null>(null);
const [inTrial, setInTrial] = useState<boolean>(false);
const [willRenew, setWillRenew] = useState<boolean>(false);
const init = useCallback((adaptyProfile: AdaptyProfile) => {
console.log('initialising');
(async () => {
try {
setPaymentProfile(adaptyProfile);
if (adaptyProfile?.accessLevels?.premium?.isActive) {
setHasPremiumAccess(true);
} else {
setHasPremiumAccess(false);
}
const subscription = Object.values(
adaptyProfile?.subscriptions || {}
)[0];
setActiveSubscription(
!isEmpty(subscription) && subscription.isActive ? subscription : null
);
setInTrial(
!isEmpty(subscription)
? subscription?.activePromotionalOfferType === 'free_trial'
: false
);
setWillRenew(
!isEmpty(subscription) && subscription.willRenew
? subscription.willRenew
: false
);
} catch (error) {
console.error('Error fetching Adapty profile:', error);
}
})();
}, []);
useEffect(() => {
(async () => {
try {
const adaptyProfile = await adapty.getProfile();
init(adaptyProfile);
} catch (error) {
console.error('Error fetching Adapty profile:', error);
}
})();
}, [init]);
const refetch = useCallback(() => {
(async () => {
try {
const adaptyProfile = await adapty.getProfile();
init(adaptyProfile);
} catch (error) {
console.error('Error fetching Adapty profile:', error);
}
})();
}, [init]);
useEffect(() => {
adapty.addEventListener('onLatestProfileLoad', (adaptyProfile) => {
init(adaptyProfile);
});
}, [init]);
return (
<ProfileContext.Provider
value={{
paymentProfile,
hasPremiumAccess,
activeSubscription,
inTrial,
refetch,
willRenew
}}
>
{children}
</ProfileContext.Provider>
);
};
export default ProfileProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment