Triggering multiple subscription functions in Ionic 3 NGRX when a single state change occurs

I have developed an Ionic 3 application that utilizes NGRX for state management purposes. The app is designed to connect to a device via BLE technology.

Within my connection page, where the BLE device is connected, I have implemented the following code:

 private connectionStateChangedCount: number;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private device: DeviceActionsDispatcherProvider) {
    this.connectionStateChangedCount = 0;
    console.log('CONNECTION - constructor ' + this.connectionStateChangedCount);
    store.select(s => s.connection).subscribe(this.connectionStateChanged.bind(this));
  }

  //  To ensure that this.device.onConnection() is only called once when the deviceConnectionState is “connected"
  connectionStateChanged(connectionStore: any) {  
    if (connectionStore.deviceConnectionState === 'connected' &&
        this.connectionStateChangedCount === 0) {
      this.connectionStateChangedCount = this.connectionStateChangedCount + 1;
      console.log('CONNECTION – connectionStateChanged  ' + this.connectionStateChangedCount);
      this.device.onConnection();
    } 
  }

Occasionally, in chrome://inspect, the following output is observed:

connection.ts:67  CONNECTION – connectionStateChanged 1 
connection.ts:67 'CONNECTION – connectionStateChanged 1

The scenario where 'CONNECTION – connectionStateChangedCount is incremented but the subscription function connectionStateChanged is called twice with connectionStateChangedCount being 1 in both instances, back-to-back, raises confusion.

An attempt was made to replace the variable connectionStateChangedCount with an unsubscribe in the if statement as a mitigation strategy to avoid additional calls to this.device.onConnection(). This solution proved unsuccessful as occasional occurrences of two calls persisted.

Additional observations include:

  1. There are no multiple calls to the connection page constructor during these incidents.
  2. This issue arises when disconnecting from the BLE device, navigating to ConnectionPage using this.nav.setRoot(ConnectionPage) in app.component.ts, and attempting to reconnect to the BLE device on the root ConnectionPage.

Insights or suggestions on why this phenomenon is happening would be greatly appreciated.

Answer №1

After some investigation, I discovered that the problem occurred when transitioning from one page to another and the NGRX subscriptions to the store(s) were not properly unsubscribed. This resulted in the connectionStateChanged event firing twice whenever I returned to the connection page.

To remedy this issue, I have now implemented an unsubscribe method for the store in ionViewWillLeave() before navigating away from the connection page.

Implementing this change has successfully resolved the issue I was facing.

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

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Is implementing client components in Server Side pages an effective strategy for optimizing SSR performance?

In order to overcome the challenge of using client-side components in server-side pages, I made the decision to create a client-side wrapper to encapsulate these components within server-side pages. This way, I can manage all API calls and data fetching on ...

Angular and WEB API experiencing issues with the update function synchronization

Currently, I'm developing a CRUD example using dotnet core and Angular. In the backend, I have implemented a function in the CarController.cs as shown below: CarController.cs [Route("UpdateCar")] [HttpPut] public IActionResult Put([ ...

Discover the process of translating words within app.routing.module.ts in Angular

Having some trouble with my Angular routing module and ngx-translate languages. I'm trying to retrieve words from the languages in this module, but the code I've attempted isn't working: import { NgModule } from '@angular/core'; im ...

Problem with Extending Jest Matchers in VS Code TypeScript

I've developed unique Jest matchers to enhance expect for handling AxiosResponse objects. Although I've followed the standard method for expanding Jest's matcher types, my custom matchers are not being recognized by TypeScript. The error di ...

Is it possible to determine the specific type of props being passed from a parent element in TypeScript?

Currently, I am working on a mobile app using TypeScript along with React Native. In order to maintain the scroll position of the previous screen, I have created a variable and used useRef() to manage the scroll functionality. I am facing an issue regardi ...

Angular: issue with form validation - password matching is not functioning as expected

I have successfully implemented the registration form with basic validations The code I used can be found in: registration.html <form #registrationForm="ngForm" (ngSubmit)="onFormSubmit()"> ... <div class="form- ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

TypeScript mandates the inclusion of either one parameter or the other, without the possibility of having neither

Consider the following type: export interface Opts { paths?: string | Array<string>, path?: string | Array<string> } The requirement is that the user must provide either 'paths' or 'path', but it is not mandatory to pa ...

How to access type properties in typescript without using the "this" keyword

Below is a snippet of code that I am working with: class Player implements OthelloPlayer { depth; constructor(depth: number) { this.depth = depth; } getMove(state: OthelloState) { return this.MinimaxDecision(stat ...

Template literal types in TypeScript and Visual Studio Code: An unbeatable duo

I'm encountering an issue while attempting to utilize literal types in Visual Studio Code. When following the example from the documentation, https://i.stack.imgur.com/V6njl.png eslint is flagging an error in the code (Parsing error: Type expected.e ...

Error code 2532 occurs when trying to access an object using square brackets in TypeScript

Encountered the ts error: Object is possibly 'undefined'.(2532) issue while trying to access the value of a field within an object, where the object key corresponds to a value in an Enum. Below is a concise example to showcase this problem: en ...

Having trouble locating node_modules post deployment?

Although the title may lead you astray, please stay with me for a moment. I've created a basic Angular2 application in Visual Studio 2015 and have now deployed it to Azure. While having node_modules in the development environment worked perfectly fi ...

What is the best way to depict object key replacements within a Typescript definition?

I currently have these types: type PossibleKeys = number | string | symbol; type ValueOf<T extends object> = T[keyof T]; type ReplaceKeys<T extends Record<PossibleKeys, any>, U extends Partial<Record<keyof T, PossibleKeys>> = ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

The functionality to generate personalized worldwide timezone pipe is not functioning

I'm completely new to Angular and I've been working on creating a custom pipe for adjusting timezones. The idea is to allow users to select their preferred timezone and have the offset applied accordingly. To start, I created a file called timez ...

What is the best way to execute a function that retrieves data from a MySQL query and then sends it back as a result in Express.js?

How can I refactor my code to efficiently call a function that returns the result of a MySQL query and send it back in an Express.js response? I am attempting to streamline my SQL queries by exporting them into individual functions to eliminate duplicatio ...

Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...

ERROR TypeError: Unable to access the 'nativeElement' property since it is undefined in Angular 5

I have encountered a problem while working on my application. Although similar issues have been asked before, I believe mine is slightly different. In my application, when a user deletes products from their cart, I want to automatically close the modal wi ...