Manage push notifications on Firebase in a React Native app

This function serves as my listener for handling firebase push notifications. The desired behavior is to intercept push notifications received in the background state and display them as local notifications instead of showing them on the device. I have successfully implemented this functionality for foreground state notifications, but I am facing an issue with setBackgroundMessageHandler where two notifications are displayed and the app is reopened, which is not the desired outcome.

I am specifically working with topics notifications.

export const NotificationListener = navigation => {

  messaging().onNotificationOpenedApp(remoteMessage => {
    console.log(
      'Notification caused app to open from background state:',
      remoteMessage?.notification,
    );
  });

  messaging()
    .getInitialNotification()
    .then(remoteMessage => {
      if (remoteMessage) {
        console.log(
          'Notification caused app to open from quit state:',
          remoteMessage?.notification,
        );
      }
    });

  messaging().setBackgroundMessageHandler(async remoteMessage => {
    console.log('Handling message in the background!', remoteMessage);
    // let title = remoteMessage?.notification?.title;
    // let body = remoteMessage?.notification?.body;
    // PushNotification.localNotification({
    //   channelId: 'burque_channel_id',
    //   title: title,
    //   message: body,
    // });
  });

  messaging().onMessage(async remoteMessage => {
    console.log('notifications on foreground state..', remoteMessage);
    let title = remoteMessage?.notification?.title;
    let body = remoteMessage?.notification?.body;
    PushNotification.localNotification({
      channelId: 'burque_channel_id',
      title: title,
      message: body,
    });
  });
};

Answer №1

When a message containing a notification element is received by the device while the application is running in the background, the notification will be displayed before any application code is executed. This behavior cannot be altered.

If you wish to have complete control over how the message is displayed within your application, it is recommended to send a message with only a data element.

For further information on this topic, please refer to the relevant section in the Firebase documentation regarding message types.

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

What are the steps to customize the index.html file within the build directory prior to serving it for each request using an Nginx server?

I need to make changes to the React index.html file on the server prior to delivering it to the browser upon request. My goal is to dynamically include open graph meta tags in the head based on the requested URL. Is there a way to accomplish this using N ...

Sending an array of arrays from JavaScript to a Spring MVC controller via AJAX

Having a bit of trouble with passing arrays within arrays. The first example below shows a simple array being passed successfully. However, when attempting to pass an array of arrays in the second example, it doesn't seem to work. Any suggestions on h ...

Retrieving form control values in AngularJS without using data binding

I recently implemented a form using rails scaffolding, which is functioning properly. However, I am now looking to enhance it by adding a new Angular controller. The purpose of this controller would be to calculate a score/progress bar that displays the pe ...

Locating the value of field in an array of JSON data

let data = [{ a: 1, b: 2}, { a: 11, b: 12}, { a: 31, b: 23}, { a: 51, b: 24}] How can you retrieve the object where a = 11 ? For simple arrays, one could use x.indexOf('1');. So a potential solution could be: let result = data.find(obj => o ...

Spring Boot is having trouble identifying the JavaScript files

I've incorporated Spring Boot in my project and I'm working with a JSP file that looks like this: <%@ include file="common/header.jsp" %> <%@ include file="common/navigation.jsp" %> <div class="container"> ...

What is the most efficient way to add multiple records to the database simultaneously?

I am currently working on a MySQL database project. On my webpage, there are multiple rows of textboxes where each row corresponds to an entry in the database. When a user enters data into a single row and clicks the save button, the values are automatica ...

Display information from a JSON file using Vue.js

Hello, I am currently attempting to display data from a JSON file using Vue.js. Below is my Vue file: <template> <div> <div class="card"> <div class="card-header"> <h4 class="card-title" ...

innovative solution for the 'vacuumCleaner' toy problem with efficient reflex agent technology

Currently, I am pursuing a BSCS degree and my focus of study is 'Artificial Intelligence'. I have developed a simple reflex agent program that operates in 'Python', but I also attempted to replicate it using p5.js (JavaScript) to creat ...

Get the docx file as a blob

When sending a docx file from the backend using Express, the code looks like this: module.exports = (req, res) => { res.status(200).sendFile(__dirname+"/output.docx") } To download and save the file as a blob in Angular, the following code snippet i ...

Translating code from Java to JavaScript with the help of the G

I am facing a challenge where I need to convert Java code into JavaScript while preserving all method, variable and parameter names. Is it possible to achieve this using the GWT compiler or any other tool available in the market? I attempted compiling the ...

Employing jQuery Mobile with MVC3 for seamless auto-submit functionality

When I remove jQuery Mobile, the code works perfectly! The form: @using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" })) { @Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town") } The Javascript: & ...

Unable to utilize the resolved value received from a promise and returned from it

Within the code snippet below, I am retrieving a Table object from mysql/xdevapi. The getSchema() and getTable() methods return objects instead of promises. The purpose of this function is to return a fulfilled Table object that can be used synchronously i ...

Is there a built-in way to update a Django template from the server side in response to an event?

As a novice Django developer, my task is to create an auction website. I need to enhance the template that displays item listings and bids, ensuring that the latest bids are updated in real-time without the need for users to refresh the page. While consid ...

While typing, React-hook-form is removing the input field when the mode property is enabled

Currently, I am implementing a basic form using react-hook-form version 7 along with Material UI. However, I have encountered an unusual behavior when configuring the mode in useForm({mode: ".."}). Below is a snippet of my code: import { yupResol ...

Creating dynamic image carousels using the latest versions of Bootstrap and AngularJS

I have created an array that stores various images using angularJS: $scope.docImg = [ '../../Content/Image/BackGrounds/abra.png', '../../Content/Image/BackGrounds/background_black.jpg', '../../Content/I ...

Exploring Angular Resource: Optimizing and shaping data in requests and responses

In my angular + closure project, I'm looking to selectively transform / intercept requests without affecting all of them in order to convert camelCase keys to snake_case. While I successfully added default interceptors and transformers through $httpP ...

How can we create dynamic keys for object properties in typescript?

Is there a way in TypeScript to convert an array of objects into an object with keys and arrays dynamically? For instance, given the following data: data1 = [ {a: 'st1', b: 1, c: 1, d: 1, e: 'e1' }, {a: 'st2', b: 2, c: 2, ...

Class for Eliminating the Background Image Using Bootstrap

Is there a Bootstrap class that can be used to remove a background image from a div? Currently, I have this style defined in my CSS: background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0)); I would like to remove it using: bg-img-non ...

Having trouble performing an Image (base64) update in Next.js

Hi everyone, I'm facing a challenge with updating the image data in my code. The base64 string data updates correctly and the new image is displayed before submitting the data. However, once I submit the data, the image doesn't update. Below is ...

Add a new controller to an already running Angular application

Recently, I developed a piece of code that integrates bootstrap modals with Angular, allowing for the loading of links into modals upon click. The challenge arose when these links contained their own Angular controllers embedded within them. While attempti ...