We seem to be encountering a problem with notifications in React Native, possibly related to background usage

Currently, I am utilizing React Native Push Notifications to schedule local notifications when my app is minimized on Android.

The issue arises when I implement the following code:

constructor(){
    super();

    this.handleAppStateChange = this.handleAppStateChange.bind(this);
    this.state = {
      seconds: 10
  };
}

componentDidMount(){
    AppState.addEventListener('change', this.handleAppStateChange);
    this.getTitles();
}

componentWillUnmount(){
  AppState.removeEventListener('change', this.handleAppStateChange);
}

handleAppStateChange(appState){
  if(appState === 'background'){
       PushNotification.localNotificationSchedule({
      message: "SUMMER SALE IS ON!", 
      date: new Date(Date.now() + (this.state.seconds * 1000)) // in 60 secs
    });
  }
}

I have implemented this code in my home.js file, which serves as my homepage with a search bar. The problem occurs when I search for something and submit it from home.js to searchResult.js (passing data with react navigation), triggering the notification on the searchResult.js page.

The notification should only trigger when my app is minimized. How can I prevent the notification from triggering in searchResult.js?

EDIT: This is my current App.js file, and I'm unsure how to incorporate the notification functionality here:

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);


import store from './store'; //Import the store

import Home from './components/home' //Import the component file
import Cart from './components/cart';
import SearchResults from './components/searchResults';

export default class App extends Component {
    render() {
        return (
            <Provider store={store}>
                <Root />
            </Provider>
        );
    }
}

const homeStack = createStackNavigator({
  Home: { 
    screen: Home, 
    navigationOptions:{
         title: "test",
       headerStyle: {
          backgroundColor: '#4050B5',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
          fontWeight: 'bold'
      }
    }
  },
   SearchResults: { 
    screen: SearchResults, 
    navigationOptions:{
         title: "Search Results",
       headerStyle: {
          backgroundColor: '#4050B5',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
          fontWeight: 'bold'
      }
    }
  }
})

const cartStack = createStackNavigator({
 Cart: {  
    screen: Cart, 
    navigationOptions:{
       title: "Shopping Cart",
     headerStyle: {
        backgroundColor: '#4050B5',
    },
    headerTintColor: '#fff',
    headerTitleStyle: {
        fontWeight: 'bold'
    }
    }
  },
})

const Root = createBottomTabNavigator({
  Home: homeStack,   
  Cart: cartStack
},    
{ 
  initialRouteName : "Home", 
},
{
    navigationOptions: ({ navigation }) => ({
      tabBarIcon: ({ focused, tintColor }) => {
        const { routeName } = navigation.state;
        let iconName;
        if (routeName === 'Home') {
          iconName = `user${focused ? '' : '-outline'}`;
        } else if (routeName === 'Cart') {
          iconName = `cart${focused ? '' : '-outline'}`;
        }

        // You can return any component that you like here! We usually use an
        // icon component from react-native-vector-icons
        //return <EvilIcons name={iconName} size={25} color={tintColor} />;
      },
    }),
    tabBarOptions: {
      activeTintColor: 'tomato',
      inactiveTintColor: 'gray',
    }
}
);

Answer №1

To efficiently manage app state changes, it is recommended to handle them at the highest level possible, such as in App.js. When using the handleAppStateChange function, make sure to pass the next app state as a parameter for better control. To achieve this, consider storing the current appState in the component's state and then compare it with the new state. Your listener should be like this:

handleAppStateChange(nextAppState)
with a conditional check like
if (this.state.appState === 'inactive' && nextAppState === 'background')
. Finally, don't forget to update the state by calling
setState({appState: nextAppState})
at the end of your listener. This approach should help resolve any issues you are experiencing, but feel free to reach out if more assistance is needed.

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

How can I set the input tag to reset back to 1 when a certain event occurs?

I am currently developing an HTML Snakes And Ladders game. On the settings screen, there is an input field where users can select the size of the board. Depending on their choice, they will be able to choose a maximum number of snakes and ladders. For exa ...

Determine the dimensions of a child layout within a ConstraintLayout

I am facing an issue with a constraint layout that includes a child layout (frame_layout). The width and height are both set as 0dp with match_constraint. After loading the layout on the screen, I'm unable to retrieve the actual height and width of th ...

Error 404 encountered when attempting to send a JSON object to the server

I've been facing a problem while trying to send a JSON object to the server using AJAX calls. I keep getting a 404 Bad Request error. The issue seems to be related to the fact that I have a form where I convert the form data into a JSON object, but th ...

Browser extension causes file upload window to appear off-screen in Chrome

Encountering a problem with the file browse dialog window displaying off-screen on a Mac while trying to upload a file through a Google Chrome extension I'm developing. Does anyone know how to relocate the dialog window or attach the file upload to th ...

AngularJS Ng-Repeat not looping through elements within $Scope

I'm currently attempting to retrieve a Json array of objects from my Employees API, and here is what is being returned: [ { "Id": "00162c3a-2b70-4f50-80e8-6fee463cffdb", "EmployeeNumber": 123, ...

Is there a way to merge various collections into a single collection using Node.js and MongoDB?

There are four collections in my database: 1. Division 2. Category 3. Product Group 4. Product The following are sample data entries from each collection: { "divisionid": "1", "divisioncode": "0", "divisionname": "ELECTRONICS/HOME APPLIA ...

Extracting information from HTML and transferring it to Javascript using jQuery

My goal is to utilize jsGrid for showcasing database data without repeating code extensively. I aim to generate separate grids for each <div> with a specific id while passing on relevant values accordingly. To clarify my objective, here's a sni ...

Utilizing a PHP Class object in Javascript by accessing its properties within a Javascript function

I'm struggling to access the attributes of an object within a JavaScript function that I created. This object was originally a PHP object that I converted to JSON using json_encode() In my project, there is 1 PHP file and 1 external JS file. In the ...

Tips for displaying a message in the model body when a bootstrap model does not have any data in jQuery

Having trouble displaying a text message in the Bootstrap modal body when there is no data available in the model. I have multiple cards in the model, and if I click on the skip or done buttons, each card will close. However, if there is only one card in t ...

Transmitting various pieces of information using AJAX

Is it possible to send both "credit_uri" and "address" strings in one AJAX request? Currently, only the second string is being sent. How can I include both in the data of the request? $.ajax({ url: '#{add_cards_path}', type: 'POST&apo ...

Changing object in Vuex mutation - a step towards state update

When a button is clicked by the user, I aim to update the data in my vuex store with the information from my local object. However, I am facing an issue with the mutation process. Below you can find some code snippets for better understanding. The followi ...

The class is failing to be applied to the parent div that holds an id starting with the letter x

I have been attempting to assign a class to the parent container when the child element has the 'hidden' class. If not, then a different class should be added. function tagMissions() { if ($('span[id^="mission_participant_new"]').h ...

javascript various backgrounds on click

I have implemented a list to allow users to select their top 3 choices, and I am using JavaScript to track these selections and change the background color accordingly. 1st selection -> Green background 2nd selection -> Yellow background 3rd sel ...

Mouse click failing to trigger CSS property update

I am attempting to create an accordion feature. I want the accordion to expand when hovering over the "accordion head," and also show/hide the accordion body when clicking on the "accordion head." I have successfully implemented the show/hide functionalit ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...

Insufficient resources - Angular 11 encountering JavaScript heap depletion during ng serve operation

Recently, I made the leap and upgraded my Angular version from 5.2 to 11.2 However, upon starting the server with (ng serve), I encountered the dreaded error message: Allocation failed - JavaScript heap out of memory To make matters more confusing, a file ...

Error in projecting D3 world-50m.json file causing fill issues

I am currently working with the world-50m.json file for a projection, but I'm facing an issue where several countries are being cut off at the edges when filled with color. This results in horizontal fill sections/lines across the map. This problem i ...

What is the best way to display a collection of images by utilizing their URLs in a React Native application

How can I display an array of images in React Native using URLs? I have tried the code below, but the images are not showing up on the screen even though the console log is displaying the image URLs correctly. { this.props.user.map((images) => ...

Moving an array in AngularJS from one file to another

As someone new to AngularJS, I am facing an issue with integrating two separate files that contain modules. Each file works fine individually - allowing me to perform operations on arrays of names. However, when switching views, the arrays remain stored un ...

What is the best way to access a key from an object within the map function?

What is the method to extract the key from an object in ReactJS? {this.state.data.map((object, index) => ( <div>{Object.keys(object)}</div> ))} For example, if this.state.data contains: [{mykey1:23},{mykey2:24},{mykey3:34}] T ...