The issue with NetInfo.addEventListener not functioning properly in a react-native environment

Utilizing the NetInfo component in react-native to monitor network state and listen to changes using NetInfo.addEventListener() function. However, I am facing an issue where the state does not update when switching between wifi and internet connections.

import React, {Component, PropTypes} from 'react';
   import {
   Platform,
   View,
   Text,
   Image,
    StyleSheet,
   AsyncStorage, 
   BackHandler,
   StatusBar  ,
   NetInfo,
  Alert
 } from 'react-native';

 // Other imports and configurations

 export default  class SplashScreen extends ComponentBase {

  constructor(props){
    super(props);
    this.state = {
        timePassed: false,
        deviceId:"",
        id:"",
        index:2,
    };
}

// Other methods and lifecycle functions

 async componentDidMount() {
       NetInfo.getConnectionInfo().then((connectionInfo) => {
    console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
  });
  function handleFirstConnectivityChange(connectionInfo) {
    console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
    NetInfo.removeEventListener(
      'connectionChange',
      handleFirstConnectivityChange
    );
  }
  NetInfo.addEventListener(
    'connectionChange',
    handleFirstConnectivityChange
  );

    firebaseNotification.analytics().setCurrentScreen("SplashScreen");
    const value = await AsyncStorage.getItem('SignInStatus');
    console.log("value is", value);

    // Notification handling logic

    tracker.trackScreenView('SplashScreen')
}

// Render method with conditional output based on timePassed state

const styles = StyleSheet.create(
   {
    MainContainer:
    {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },

    SplashScreen_RootView:
    {
        justifyContent: 'center',
        flex:1,
        position: 'absolute',
        width: '100%',
        height: '100%',

    },

    SplashScreen_ChildView:
    {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#1F0242',
        flex:1,
    },

    TouchableOpacity_Style:{
        width:25, 
        height: 25, 
        top:9, 
        right:9, 
        position: 'absolute'
    }
});

Despite including the code in the componentDidMount() method, only the initial connection info is logged and not the listener via NetInfo.addEventListener(). Seeking assistance to resolve this issue.

Answer №1

Ensure that you have the appropriate permissions set...

For Android:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Answer №2

Initially: It is advisable to attach the EventListener before the mounting of your component (componentWillMount) and detach it before unmounting (componentWillUnmount).

Another factor to consider: Why should your component trigger an update and display console.log when there is no change in state? The handleConnectionChange method currently has no functionality. Start by updating that and storing the value (isConnected) in your component's state.

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

The error message states: `discord.js TypeError: Unable to access the property 'resolve' as it is undefined`

Encountering an issue with the following code snippet const Discord = require('discord.js'); module.exports = { name: 'info', description: "Shows BOT's Informations", execute(message, client, args) { c ...

What is the best way to transfer attribute values from multiple elements and paste them each into a separate element?

I have multiple elements with the tag <a class="banner2">. Each of these elements has a different URL for the background image and href value. <a href="#" target="_blank" class="banner2" style="background-image:url('<?php echo get_templat ...

Getting the vertices of a sphereGeometry can be achieved by accessing the specific

While it may seem like an easy question, I am looking to place objects on top of the vertices of a sphere in Three.js. Each sphere is made up of small triangles, and I specifically need the coordinates of these corners/vertices rather than random locations ...

Attaching an Event Listener to an array

I am struggling with a homework assignment and don't understand why I am receiving an error message saying 'undefined is not an object (evaluating 'buttons[i].style')). Any help would be appreciated. I have been attempting to loop throu ...

Acquire Content using jQuery and Navigate page horizontally

I am trying to achieve a unique effect by capturing content x and horizontally scrolling the page while the mouse is in motion, similar to swiping on a tablet. It seems simple enough.. Capture clientX on mousedown, ScrollLeft by ClientX while moving, Di ...

Having Trouble with Unevenly Spaced Child Elements in CSS Flexbox?

I'm running into a problem while utilizing CSS Flexbox to design a layout with multiple child elements. The issue at hand is that the child elements are not aligning correctly within the parent container. I aim for them to be evenly distributed and ce ...

Is there a way to unshackle myself from the promise chain in Express and trigger an error ahead of time

Upon examining my request handler, it appears as follows: router.post('/', function(req,res) { var screencast; var channel; youtube.get(req.body.videoId).then(function(data) { screencast = data.screencast; channel = data.channel; ...

Having issues with referencing external JavaScript and CSS files in Angular 6

Dealing with an angular6 project and a bootstrap admin dashboard template, I'm facing issues importing the external js references into my Angular application. Looking for guidance on how to properly import and refer to external Js/CSS files in an angu ...

Saving a dataUrl encoded as base64 to a file in Electron

I am currently working on enhancing an existing Electron project by transforming a web app into a desktop application. One of the tasks I have is to enable users to export content from the screen to PDF, PNG, or JPG formats. Here's the scenario: Th ...

Guide to organizing a calculated attribute in vue.js

I'm struggling with organizing the already computed array of results. Within Vue, I have successfully filtered images based on their ratio. Now, my goal is to sort these filtered results by date, name, or any other possible category. Although I atte ...

The functionality of List.js is currently not optimized for use with tables

I'm currently experimenting with list.js in order to create a real-time search feature for a table. I have successfully tested it on lists (similar to the example provided at ). However, I am facing difficulty replicating this functionality for tables ...

The Owl carousel's autoplay feature seems to be set at a fixed speed of 5

I've been attempting to adjust the autoplay speed on an owl carousel (specifically using owl carousel 1), but no matter what integer I add after autoplay:, it remains stuck at 5 seconds. The website, which is currently broken, suggests that adding a n ...

Creating customized JavaScript using jQuery for Drupal 7 Form API

Currently, I am working on developing a custom form using Drupal 7 with form API and a tableselect that includes checkboxes. I have some specific constraints for selecting the checkboxes that I intend to implement using jQuery. I created a function for han ...

Tips for concealing the loader once all pages have been loaded

Within the context of my website development project at , I am utilizing a script for infinite scrolling to consolidate multiple pages into one seamless scrolling experience. I am seeking a solution to hide the loader (the spinning icon) when no additiona ...

Trouble with ScrollTo animation on div with adjustable offset top feature - seeking assistance

Having trouble navigating to the correct slide when clicking the right button on the navigation menu. Clicking the menu button displays a list of links. Clicking on a link for the first time will take you to the correct slide, but if you try clicking a dif ...

Save Scope in JSON format

Currently, I am developing a web application that dynamically displays specific prompts based on the field in focus. There are several different texts stored as scripts that I want to showcase at these different points. My goal is to incorporate scope dat ...

Enhancing an existing Express project with socket.io (plus a side of React)

I have been working on a project with Express, which includes a messaging system. Initially, everything was functional with POST/GET methods for sending and receiving messages. However, I wanted to implement real-time messaging by integrating socket.io on ...

Dealing with nested JSON objects in NodeJS may result in the return of [Object

I'm trying to extract nested JSON objects from a JSON array, but instead of getting the actual objects, I'm seeing [Object]. Here's an example of my JSON structure: var json = { "root_id": [ { "child-id1": { "name": "nam ...

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

`Can you guide me on transferring an audio blob from javascript to python?`

My goal is to transfer an audio blob from JavaScript to a Python script running on the server. Below is a snippet of my AJAX code in JavaScript: var fileType = 'audio'; var fileName = 'output.wav'; var formData = new FormData(); formDa ...