When using a RewardedAd instance multiple times, ad doesn't load or show, without error...
Plus, state is wrong because we can't know for sure if ad is loaded or not.
Related to #3748 and #3185
Here is my component :
import React from "react";
import { Button } from "react-native";
import {
RewardedAd,
TestIds,
RewardedAdEventType,
AdEventType,
} from "@react-native-firebase/admob";
const adRewardedId = __DEV__ ? TestIds.REWARDED : "your-admod-ad-id";
const rewardedAd = RewardedAd.createForAdRequest(adRewardedId, {
requestNonPersonalizedAdsOnly: true,
});
export default () => {
const [rewardedAdLoaded, setRewardedAdLoaded] = React.useState(false);
React.useEffect(() => {
const eventListener = rewardedAd.onAdEvent(async (type, error, reward) => {
if (type === RewardedAdEventType.LOADED) {
setRewardedAdLoaded(true);
}
if (type === RewardedAdEventType.EARNED_REWARD) {
console.log("rewarded with ", reward);
}
if (type === AdEventType.OPENED) {
setRewardedAdLoaded(false);
}
if (type === AdEventType.CLOSED) {
setRewardedAdLoaded(false);
rewardedAd.load();
}
});
// Start loading the rewarded ad straight away
if (rewardedAd.loaded) {
setRewardedAdLoaded(true);
} else {
rewardedAd.load();
}
// Unsubscribe from events on unmount
return () => {
eventListener();
};
}, []);
return (
<Button
disabled={!rewardedAdLoaded}
onPress={() => {
rewardedAd.show();
}}
>
{rewardedAdLoaded ? "Watch ad" : "Loading..."}
</Button>
);
};
Click To Expand
#### `package.json`: ```json{ "name": "app", "version": "1.0.0", "private": true, "scripts": { "android": "react-native run-android", "build-android": "cd android && gradlew bundleRelease", "test-release": "react-native run-android --variant=release", "gradle-clean": "cd android && gradlew clean", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint . --ext .js,.jsx --fix", "lint-fix": "eslint . --ext .js,.jsx --fix", "format": "prettier --write ./src" }, "dependencies": { "@eva-design/eva": "2.0.0", "@react-native-community/async-storage": "^1.12.0", "@react-native-community/masked-view": "^0.1.10", "@react-native-firebase/admob": "^7.6.5", "@react-native-firebase/app": "^8.4.3", "@react-navigation/native": "^5.7.3", "@react-navigation/stack": "^5.9.0", "@ui-kitten/components": "5.0.0", "@ui-kitten/eva-icons": "5.0.0", "@ui-kitten/metro-config": "^5.0.0", "js-levenshtein": "^1.1.6", "lottie-react-native": "^3.5.0", "react": "16.11.0", "react-native": "0.62.2", "react-native-config": "^1.3.3", "react-native-device-info": "^5.6.5", "react-native-gesture-handler": "^1.7.0", "react-native-google-play-game-services": "github:jeremyhalin/react-native-google-play-game-services", "react-native-iap": "^4.5.3", "react-native-onesignal": "^3.9.1", "react-native-reanimated": "^1.13.0", "react-native-safe-area-context": "^3.1.7", "react-native-screens": "^2.10.1", "react-native-share": "^3.8.3", "react-native-splash-screen": "^3.2.0", "react-native-svg": "^12.1.0", "react-native-swipe-gestures": "^1.0.5", "realm": "^6.1.0" }, "devDependencies": { "@babel/core": "^7.11.6", "@babel/runtime": "^7.11.2", "babel-eslint": "^10.1.0", "babel-jest": "^24.9.0", "babel-plugin-transform-remove-console": "^6.9.4", "eslint": "^7.10.0", "eslint-config-airbnb": "^18.2.0", "eslint-config-prettier": "^6.12.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jsx-a11y": "^6.3.1", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-react": "^7.21.3", "eslint-plugin-react-native": "^3.10.0", "metro-react-native-babel-preset": "^0.58.0", "prettier": "^2.1.2", "react-native-svg-transformer": "^0.14.3", "react-test-renderer": "16.11.0" }, "jest": { "preset": "react-native", "transformIgnorePatterns": [] } }
#### `firebase.json` for react-native-firebase v6:
```json
{
"react-native": {
"admob_android_app_id": "ca-app-pub-********",
"admob_ios_app_id": ""
}
}
### iOS
#### `ios/Podfile`: - [x] I'm not using Pods - [ ] I'm using Pods and my Podfile looks like:
# N/A
#### `AppDelegate.m`:
// N/A
Click To Expand
#### Have you converted to AndroidX? - [x] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 29
supportLibVersion = "28.0.0"
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.5.2")
classpath 'com.google.gms:google-services:4.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
url 'https://maven.google.com'
}
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
ext {
gms_library_version = '17.0.0'
}
}
#### `android/app/build.gradle`:
buildscript {
repositories {
maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
}
dependencies {
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
}
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'
project.ext.envConfigFiles = [
debug: ".env.development",
release: ".env.production",
]
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation. If none specified and
* // "index.android.js" exists, it will be used. Otherwise "index.js" is
* // default. Can be overridden with ENTRY_FILE environment variable.
* entryFile: "index.android.js",
*
* // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
enableHermes: false, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.memorablequotes"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 34
versionName "2.0.3"
multiDexEnabled true
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
storeFile file(MYAPP_UPLOAD_STORE_FILE)
storePassword MYAPP_UPLOAD_STORE_PASSWORD
keyAlias MYAPP_UPLOAD_KEY_ALIAS
keyPassword MYAPP_UPLOAD_KEY_PASSWORD
}
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
packagingOptions {
pickFirst "lib/armeabi-v7a/libc++_shared.so"
pickFirst "lib/arm64-v8a/libc++_shared.so"
pickFirst "lib/x86/libc++_shared.so"
pickFirst "lib/x86_64/libc++_shared.so"
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
implementation "com.google.android.gms:play-services-games:${gms_library_version}"
implementation "com.google.android.gms:play-services-auth:${gms_library_version}"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
#### `android/settings.gradle`:
rootProject.name = 'App'
include ':react-native-vector-icons'
project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
include ':react-native-onesignal'
project(':react-native-onesignal').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-onesignal/android')
include ':react-native-config'
project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':lottie-react-native'
project(':lottie-react-native').projectDir = new File(rootProject.projectDir, '../node_modules/lottie-react-native/src/android')
include ':react-native-splash-screen'
project(':react-native-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-splash-screen/android')
include ':react-native-iap'
project(':react-native-iap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-iap/android')
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
#### `MainApplication.java`:
package com.myapp;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;
import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.airbnb.android.react.lottie.LottiePackage;
import org.devio.rn.splashscreen.SplashScreenReactPackage;
import com.dooboolab.RNIap.RNIapPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.myapp.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
#### `AndroidManifest.xml`:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.android.vending.BILLING" />
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-***"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
<meta-data
android:name="com.google.android.gms.games.APP_ID"
android:value="@string/app_id" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
Click To Expand
**`react-native info` output:**
System:
OS: Windows 10 10.0.19041
CPU: (16) x64 AMD Ryzen 7 2700X Eight-Core Processor
Memory: 8.19 GB / 15.95 GB
Binaries:
Node: 14.8.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.14.7 - C:\Program Files\nodejs\npm.CMD
Watchman: Not Found
SDKs:
Android SDK:
API Levels: 23, 28, 29, 30
Build Tools: 28.0.3, 29.0.2, 30.0.0
System Images: android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom
Android NDK: Not Found
Windows SDK:
AllowAllTrustedApps: Disabled
IDEs:
Android Studio: Version 4.0.0.0 AI-193.6911.18.40.6626763
Visual Studio: 16.4.29905.134 (Visual Studio Community�2019)
Languages:
Java: Not Found
Python: Not Found
npmPackages:
@react-native-community/cli: Not Found
react: 16.11.0 => 16.11.0
react-native: 0.62.2 => 0.62.2
react-native-windows: Not Found
npmGlobalPackages:
*react-native*: Not Found
- **Platform that you're experiencing the issue on**:
- [ ] iOS
- [ ] Android
- [ ] **iOS** but have not tested behavior on Android
- [x] **Android** but have not tested behavior on iOS
- [ ] Both
- **`react-native-firebase` version you're using that has this issue:**
- `8.4.3`
- **`Firebase` module(s) you're using that has the issue:**
- `admob:7.6.5`
- **Are you using `TypeScript`?**
- `N` & `VERSION`
React Native Firebase
and Invertase
on Twitter for updates on the library.Hi there!
Could you reduce this to a single App.js that we could drop into an empty triage project? This isn't executable and I don't see anything immediately wrong but that's no indication of anything unfortunately
Separately (and something you can do without waiting on anyone) you can just react into node_modules @react-native-firebase/admob
library and troubleshoot this yourself with console.log tracing of all the execution paths, that will likely be your fastest path to resolution either way - I don't use admob personally and sadly we don't get much community involvement on admob issues so there aren't many eyes available to help with issues
Side note: as the react-native-device-info maintainer I'm surprised to see that in your settings.gradle? I'm also surprised to see pre-androidx multidex and support library references, those seem off to me but are likely not related at all, I just noticed them
@mikehardy
Thanks for you answer.
I've updated the component so it can be drop into a project. Tell me if it's ok.
I've tried looking at library's code without success.
I think something is wrong with this._loaded
here :
https://github.com/invertase/react-native-firebase/blob/d36e71605ebdd8337f3662f1c1a709d63c3947a9/packages/admob/lib/ads/RewardedAd.js#L46-L50
Does the value is set to false
when ad has been seen?
I don't have any crash, when I press the button to see RewardedAd multiple times, it's just that nothing happen.
About the side note, there shouldn't be anything in my settings.gradle?
Didn't get your second note, but I would be very happy to have your feedback. I'm not quite comfortable with .gradle
files 😄
I have the same issues and even same my code.
You should recreate new RewardedAd
instance when you want to show new Ad. official
Closing this issue because best practice is to create a new instance each time we want to display a RewardedAd.
Most helpful comment
You should recreate new
RewardedAd
instance when you want to show new Ad. official