Acquiring the Firebase Cloud Messaging token within a React Native environment

As a beginner in the world of react native, I am exploring how to incorporate background notifications into my app. After conducting some research, it seems like using Firebase Cloud Messaging would be the most suitable approach for this.

After going through various tutorials, I have implemented the following code snippet:

export default class App extends React.Component { 
  requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      if (enabled) {
        getFcmToken();
        console.log('Authorization status:', authStatus);
      }
    };

    getFcmToken = async () => {
      const fcmToken = await messaging().getToken();
      if (fcmToken) {
          console.log(fcmToken);
          console.log("Your Firebase Token is:", fcmToken);
      } else {
          console.log("Failed", "No Token Recived");
      }
    };

    async componentDidMount() {
      await this.requestUserPermission();

       // Register background handler
       messaging().setBackgroundMessageHandler(async (remoteMessage) => {
       console.log('Messaage handled in the background!', remoteMessage);
  });
};
  }

However, upon testing the app on my iOS device, I encountered an error message in the terminal stating:

ReferenceError: Can't find variable: getFcmToken

Furthermore, when attempting to send a test notification, it does not appear as expected.

My query is: Could there be an issue in my code implementation or have I overlooked something?

Answer №1

Make sure to declare the function getFcmToken before you call it in your code.

    // First, declare getFcmToken
    const getFcmToken = async () => {
      const fcmToken = await messaging().getToken();
      if (fcmToken) {
          console.log(fcmToken);
          console.log("Your Firebase Token is:", fcmToken);
      } else {
          console.log("Failed", "No Token Received");
      }
    };

    // Then, proceed to use it
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      if (enabled) {
        getFcmToken();
        console.log('Authorization status:', authStatus);
      }
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a 403 error when attempting to upload files from Angular to a Micron

I have encountered an issue while attempting to upload multiple files to the Micronaut Rest API. The uploading process works seamlessly with Postman and Swagger in the Micronaut Rest API, but when using the Angular app, the POST method throws a 403 HTTP er ...

Show the data from the chosen array using Vue JS

Just diving into Vue JS and eager to master it through creating a simple note-taking app. The concept is straightforward - a list of all notes (their titles) on the left, and when you click on a note title, the corresponding note text is displayed in a te ...

Navigate to the following section on an HTML page by clicking a button using jQuery

Within my application using Jquery / Javascript, I am looking to implement a specific functionality. I currently have several div elements like the ones below: <div id="div1"></div> <div id="div2"></div> <div id="div3"></ ...

The homepage emerges as the splash site disappears

I have implemented a script to smoothly transition between pages: $(document).ready(function() { $("body").css("display", "none"); $("body").fadeIn(650); $("a:not([href^='#'])").click(function(event){ event.preventDefault(); ...

MVC3: Easily browse through tables by accessing details directly from the details view, eliminating the need to click on

I am currently working on an Index view where a table displays a list of items, each with a link to show its details in another partialview loaded through Ajax. Users have expressed interest in being able to easily navigate between "Next Item" and "Previo ...

Bootstrap 4's Datetime picker not appearing as expected

I'm currently facing an issue with integrating the EONASDAN datetime picker form into my Bootstrap v4 webpage. The GET form I have contains a lot of data to be submitted. In the demo page provided below, I want users to make selections in each text ...

Arranged list becomes depleted (Although Lodash's groupBy function still functions properly)

Check out the sample plunker here Initially, I am grouping a collection by a specific key, which in this case is yob (year of birth). I have two approaches: I can create a custom function to group the collection, allowing for custom logic to be impleme ...

Attempting to trigger the onchange function established by jQuery

Within my code, I have a change listener set on the checkboxes in this section: $(".section").change(function() { if($(this).is(":checked")) { $("." + this.id).show(); ... Now, I am attempting to simulate a click event on the ch ...

Exploring the differences between an XMLHTTP request and a string and establishing a callback mechanism

After being a silent observer for quite some time, I've finally mustered up the courage to make my first post here, so please be kind... My journey with Javascript has just begun, and although I plan on delving into jQuery eventually, for now, I am f ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

Steer clear of changing props directly in VueJS to prevent unintended

I am working with a component that has props, and I need to change the value from false to true. However, I encountered a message in the Chrome console advising against mutating a prop directly because it will be overwritten whenever the parent component r ...

Separate your export function calls into their own dedicated file

Currently, I have a function defined in my app.js. The goal now is to separate the function calls into a different file. // Function to add .rellax class and data attribute function addRellax(selector, value) { // Select all elements that match the giv ...

Close button for colorbox modal window containing an iframe

I'm currently utilizing colorbox for a modal popup, and the content of the popup is being sourced from a URL. Since it's displayed within an iFrame, I'm wondering how I can incorporate a close button to the modal popup. Thank you The follo ...

Animating the background color of an SKScene using Objective C

Is there a way to animate the background color of an SKScene in Sprite-Kit? I attempted using UIView animate without success. Is there a similar method for Sprite-Kit? I am searching for a solution like this, but tailored for Sprite-Kit: [UIView animateW ...

Tips for updating a single parameter with vue router-link

I am facing an issue with my user list and calendar components. Whenever I click on a user link, I want only the selectedUser parameter in the URL to change while leaving all other parameters unchanged. Currently, when I click on the "Change date" link, i ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

Bizarre text scenarios in JavaScript

I've come across something similar in certain libraries if ("testing" !== 'production') { "testing" !== 'production' ? warning(this instanceof Constructor, 'A React component is being called directly. Consider using ...

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

Using both a button and a link simultaneously in react is not possible

I have a single page app that consists of 4 different components, each of them requiring a submit button to save and send data within the form. However, I am facing an issue where using the submit button only submits the information, but I also need to in ...

Cross-origin Resource Sharing (CORS) with Firebase

Initially, I successfully implemented Firebase Functions with the Ionic Native HTTP plugin (https://ionicframework.com/docs/native/http/). However, I recently decided to transition to the Angular-Http method to allow for easier testing in the browser. The ...