Skip to content

Instantly share code, notes, and snippets.

@erenkulaksiz
Created April 27, 2024 06:26
Show Gist options
  • Save erenkulaksiz/a3036ea09e9e32389a3e6530a1db0f4c to your computer and use it in GitHub Desktop.
Save erenkulaksiz/a3036ea09e9e32389a3e6530a1db0f4c to your computer and use it in GitHub Desktop.
import { useEffect, useRef, useState } from "react";
import { AdEventType, InterstitialAd } from "react-native-google-mobile-ads";
import analytics from "@react-native-firebase/analytics";
import adId from "@/utils/adId";
import { useAuthStore } from "@/stores/authStore";
import isPremium from "@/utils/isPremium";
interface IUseInterstitialAd {
onAdLoaded?: (showAd: () => void) => void;
onAdWatched?: () => void;
}
export default function useInterstitialAd({
onAdLoaded,
onAdWatched,
}: IUseInterstitialAd = {}) {
const validatedUser = useAuthStore((state) => state.validatedUser);
const [loadedAd, setLoadedAd] = useState(false);
const ad = useRef<InterstitialAd>(
InterstitialAd.createForAdRequest(adId().INTERSTITIAL)
);
useEffect(() => {
ad.current.addAdEventListener(AdEventType.LOADED, () => {
console.log("ad loaded");
setLoadedAd(true);
if (typeof onAdLoaded === "function") {
onAdLoaded(showAd);
}
});
ad.current.addAdEventListener(AdEventType.CLOSED, async () => {
console.log("ad closed");
await analytics().logEvent("ad_watched", {
userId: validatedUser?.uid,
});
if (typeof onAdWatched === "function") {
onAdWatched();
}
});
ad.current.load();
return () => {
ad.current.removeAllListeners();
};
}, []);
function loadAd() {
ad.current.load();
}
function showAd() {
if (!isPremium(validatedUser)) {
console.log("showing ad");
ad.current.show();
}
}
return { loadAd, showAd, loadedAd };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment