React-native-firebase: [馃悰] Bug Report Title - Unable to run messaging's requestUserPermission

Created on 21 Sep 2020  路  5Comments  路  Source: invertase/react-native-firebase


Issue



Describe your issue here

I'm trying to set up react-native-firebase messaging so I can send push notifications. As a start I decided to try the requestUserPermission function to see if I will get a response. I'm coding for android so I expect that authorization status will already be granted. However, what I'm getting is a syntax error I can't explain Unexpected token (.
Here is the App.js code

Imports
...
import messaging from '@react-native-firebase/messaging';

...

class App extends React.Component {
  constructor(props) {
     // code here
  }

  async function requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      console.log('Authorization status:', authStatus);
    }
  }

  componentDidMount() {
    this.unsubscribe.auth = auth().onAuthStateChanged(async user => {
      if (!user) {
        await auth()
          .signInAnonymously()
          .then(async userCredential => {
            // Create an anonymous user profile to keep track of the seen challenges and other usage data.
            // Gets converted into a real profile once the user signs up.
            return firestore()
              .collection('users')
              .doc(userCredential.user.uid)
              .set({ createDate: new Date() });
          })
          .catch(e => console.error(e));
      }
      this.attachUserListeners();
      if (this.state.isInitializing) {
        this.setState({ isInitializing: false });
      }
    });
  }

  attachUserListeners = () => {
    // Listen to user doc:
    this.unsubscribe.user = listenToUser(userProfile =>
      this.setState({ user: userProfile }),
    );
    const userID = auth().currentUser.uid;
    // Listen to the user's subcollections:
    const collectionsToListen = ['challengeStatuses', 'follows'];
    collectionsToListen.forEach(collection => {
      this.unsubscribe[
        collection
      ] = attachCollectionListener(`users/${userID}/${collection}`, data =>
        this.setState({ [collection]: data }),
      );
    });
  };

  componentWillUnmount() {
    // Remove all database listeners:
    Object.keys(this.unsubscribe).forEach(key => {
      if (this.unsubscribe[key]) {
        this.unsubscribe[key]();
      }
    });
  }

  render() {
     // some code here
  }
}

export default App;

I get this error
Screenshot 2020-09-21 at 20 19 20

Project Files






Javascript

Click To Expand

#### `package.json`:

{
  "name": "xxxxxx",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx"
  },
  "dependencies": {
    "@react-native-community/cameraroll": "^4.0.0",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-native-firebase/app": "^8.3.1",
    "@react-native-firebase/auth": "^9.0.0",
    "@react-native-firebase/firestore": "^7.5.3",
    "@react-native-firebase/functions": "^7.3.2",
    "@react-native-firebase/messaging": "^7.8.6",
    "@react-native-firebase/storage": "^7.3.3",
    "@react-navigation/bottom-tabs": "^5.8.0",
    "@react-navigation/native": "^5.7.3",
    "@react-navigation/stack": "^5.9.0",
    "@types/lodash": "^4.14.161",
    "dayjs": "^1.8.35",
    "lodash": "^4.17.20",
    "path": "^0.12.7",
    "react": "16.13.1",
    "react-devtools": "^4.8.2",
    "react-native": "0.63.2",
    "react-native-bootsplash": "^2.2.5",
    "react-native-camera": "^3.37.0",
    "react-native-fast-image": "^8.3.2",
    "react-native-flip-card": "^3.5.6",
    "react-native-gesture-handler": "^1.8.0",
    "react-native-image-picker": "^2.3.3",
    "react-native-keyboard-aware-scroll-view": "^0.9.2",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-modal": "^11.5.6",
    "react-native-progress": "^4.1.2",
    "react-native-reanimated": "^1.13.0",
    "react-native-safe-area-context": "^3.1.6",
    "react-native-screens": "^2.10.1",
    "react-native-tab-view": "^2.15.1",
    "react-native-vector-icons": "^7.0.0",
    "react-native-video": "^5.1.0-alpha8",
    "yup": "^0.29.3"
  },
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/runtime": "^7.8.4",
    "@react-native-community/eslint-config": "^1.1.0",
    "@types/jest": "^25.2.3",
    "@types/react-native": "^0.63.2",
    "@types/react-native-vector-icons": "^6.4.5",
    "@types/react-test-renderer": "^16.9.2",
    "@types/yup": "^0.29.6",
    "@typescript-eslint/eslint-plugin": "^2.27.0",
    "@typescript-eslint/parser": "^2.27.0",
    "babel-jest": "^25.1.0",
    "eslint": "^6.5.1",
    "jest": "^25.1.0",
    "metro-react-native-babel-preset": "^0.59.0",
    "prettier": "^2.0.4",
    "react-test-renderer": "16.13.1",
    "typescript": "^3.8.3"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  },
  "prettier": {
    "trailingComma": "all",
    "bracketSpacing": true,
    "arrowParens": "avoid",
    "singleQuote": true
  }
}
#### `firebase.json` for react-native-firebase v6:
{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint",
      "npm --prefix \"$RESOURCE_DIR\" run build"
    ]
  },
  "storage": {
    "rules": "storage.rules"
  }
}
### iOS
Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like:

# N/A
#### `AppDelegate.m`:
// N/A


Android

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 = "29.0.2"
        minSdkVersion = 16
        compileSdkVersion = 29
        targetSdkVersion = 29
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.5.3")
        classpath 'com.google.gms:google-services:4.2.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        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' }
    }
}
#### `android/app/build.gradle`:
apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'

import com.android.build.OutputFile

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

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 "xxxx"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        missingDimensionStrategy 'react-native-camera', 'general'
        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'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // 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 fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation 'com.google.firebase:firebase-analytics:17.5.0'

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    implementation 'com.android.support:multidex:1.0.3'

    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'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    implementation "androidx.appcompat:appcompat:1.0.0"

    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)
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
#### `android/settings.gradle`:
rootProject.name = 'ChallengeMe'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

include ':react-native-video'
project(':react-native-video').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-video/android-exoplayer')
#### `MainApplication.java`:
package com.xxxxxxxxx.app;

import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
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;
import com.brentvatne.react.ReactVideoPackage;

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 ReactVideoPackage());

          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.challengeme.app.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.xxxxxxxx.app">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize">
        <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>


Environment

Click To Expand

**`react-native info` output:**

 info Fetching system and libraries information...
(node:7288) Warning: Accessing non-existent property 'padLevels' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
System:
    OS: macOS 10.15.4
    CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
    Memory: 102.58 MB / 16.00 GB
    Shell: 3.2.57 - /bin/bash
  Binaries:
    Node: 14.11.0 - /usr/local/bin/node
    Yarn: 1.22.4 - /usr/local/bin/yarn
    npm: 6.14.8 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.9.3 - /Users/edkahara/.rvm/gems/ruby-2.7.0/bin/pod
  SDKs:
    iOS SDK: Not Found
    Android SDK:
      API Levels: 28, 29, 30
      Build Tools: 28.0.3, 29.0.2, 30.0.2
      System Images: android-28 | Intel x86 Atom_64, android-28 | Google Play Intel x86 Atom, android-30 | Google Play Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 4.0 AI-193.6911.18.40.6626763
    Xcode: /undefined - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_242-release - /usr/bin/javac
    Python: 3.7.6 - /usr/local/anaconda3/bin/python
  npmPackages:
    @react-native-community/cli: Not Found
    react: 16.13.1 => 16.13.1 
    react-native: 0.63.2 => 0.63.2 
  npmGlobalPackages:
    *react-native*: Not Found
- **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [ ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `8.3.1` - **`Firebase` module(s) you're using that has the issue:** - `messaging version 7.8.6` - **Are you using `TypeScript`?** - `Y` & `3.8.3`




Needs Triage Bug

All 5 comments

This appears to be a syntax error, i.e. simply invalid javascript.
For this to be an issue here, you need to demonstrate react-native-firebase has a bug, not that you have a javascript problem

You may reference the end-to-end test app here in general for usage examples, as well as the docs of course.

https://github.com/invertase/react-native-firebase/blob/master/packages/messaging/e2e/messaging.e2e.js#L79-L83

But we do not debug project-specific problems in general. We can reopen if there is a problem with the module

@mikehardy Thanks for the response. So you were right, it was a javascript issue but it was also a @react-native-firebase/messaging version issue. First, the javascript issue was fixed by:

requestUserPermission = async() => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      console.log('Authorization status:', authStatus);
    }
  }

componentDidMount() {
  this.requestUserPermission
}

Then I got an Unhandled Promise error that basically tells me to do this:

=> mainAppliction.java

import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;

and add package

packages.add(new RNFirebaseMessagingPackage());

This is a weird error for @react-native-firebase/messaging 7.7.0 to have as it is basically a v5 or previous type error. I solved it by upgrading @react-native-firebase/messaging to 7.6.1 after seeing it on the github I got from this tutorial. I had initially installed version 7.8.6, which doesn't work because after running react-native run-android with it installed get the error below.
Screenshot 2020-09-22 at 08 08 19

Also, I've edited the App.js code I had posted in the issue description to remove some sensitive parts of the code. Thank you

I'm working on a project that is already set up by others, so I just had to add the messaging package. The version
https://github.com/mikehardy/rnfbdemo/blob/master/make-demo.sh#L94 installs with that command is probably 7.8.6, which sends that error when I run react-native run-android. So I had to install 7.6.1 specifically with yarn add @react-native-firebase/[email protected].

@edkahara I don't know what is wrong with your current project, and why your versions have interdependent failures, but I imagine they are not all up to date. Run the script I linked. Prove to yourself it works. Investigate your project to find the error in your project and fix it, and you'll be good to go on current stable versions like the rest of the user base

Was this page helpful?
0 / 5 - 0 ratings

Related issues

romreed picture romreed  路  3Comments

mahyarr picture mahyarr  路  3Comments

rtman picture rtman  路  3Comments

escobar5 picture escobar5  路  3Comments

n-scope picture n-scope  路  3Comments