Transmitting Events to JavaScript from Your Custom Module in React Native?

I've been attempting to transfer an event from my module to React Native. I followed the steps outlined here, but it didn't behave as anticipated. I'm not getting any errors, but it simply isn't functioning.

Below is my code in Android Studio within my module:

package com.coinboxcollector;

import android.util.Log;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.DeviceEventManagerModule;

@ReactModule(name = CoinboxCollectorModule.NAME)
public class CoinboxCollectorModule extends ReactContextBaseJavaModule {
  public static final String NAME = "CoinboxCollector";

  public CoinboxCollectorModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @NonNull
  @Override
  public String getName() {
    return "CoinBoxCollector";
  }

  private static String port="/dev/tty.usbserial-fa14";
  public MyCCT cct;
  public CoinObserver coinObserver =  new CoinObserver() {
    private ReactContext reactContext;
    @Override
    public void update(MyCCT cct, float coin) {
      Log.d("Coin", Float.toString(coin));
      try {
        this.reactContext
          .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
          .emit("onReceivedCoin", coin);
      }catch (Exception ex){
      }
    }
  };

  @ReactMethod
  public void initialize(Promise promise)
  {
    try{
      Log.d("stato", "inizializzazione ");
      if(cct == null){
        cct = new MyCCT(port, this.getReactApplicationContext());
      }
      cct.addCoinObserver(coinObserver);
      cct.start();
      promise.resolve(true);
    }catch (Exception err){
      promise.resolve(false);

    }
  }

  @ReactMethod
  public void stop(Promise promise)
  {
    try{
      cct.stop();
      cct = null;
      promise.resolve(true);
    }catch (Exception err){
      promise.resolve(false);
    }
  }

  @ReactMethod
  public void addListener(String eventName) {

  }

  @ReactMethod
  public void removeListeners(Integer count) {

  }

  @ReactMethod
  public void multiply(double a, double b, Promise promise) {
    promise.resolve(a * b);
  }
}

My code in React Native:

import {useNavigation} from '@react-navigation/native';
import React, {useEffect, useRef, useState} from 'react';
import {
  Alert,
  DeviceEventEmitter,
  NativeEventEmitter,
  NativeModules,
  Pressable,
  StyleSheet,
  Text,
  View,
} from 'react-native';
const {CoinBoxCollector} = NativeModules;

export default function HomeScreen() {
  const [off, setOff] = useState(true);

  const navigation = useNavigation();

  let coinInserted = 0;
  const coinValueStartExperience = 2;

  async function onCoinDetected(coin: any) {
    Alert.alert('ricevuti soldi', coin);
    console.log('ricevuti soldi');
  }

  const pressInit = async () => {
    return await CoinBoxCollector.initialize();
  };

  const pressStop = async () => {
    return await CoinBoxCollector.stop();
  };

  useEffect(() => {
    const eventEmitter = new NativeEventEmitter(NativeModules.CoinBoxCollector);
    const eventListener = eventEmitter.addListener(
      'onReceivedCoin',
      onCoinDetected,
    );
    return eventListener.remove();
  }, []);

  return (
    <View style={styles.container}>
      <Pressable style={styles.btn} onPress={pressInit}>
        <Text style={styles.btnText}>Initialize</Text>
      </Pressable>
      <Pressable style={styles.btn} onPress={pressStop}>
        <Text style={styles.btnText}>Stop it</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignContent: 'center',
  },
  btn: {
    marginTop: 30,
    backgroundColor: '#841584',
    width: '5%',
    height: 30,
    marginLeft: '48%',
  },
  btnText: {
    color: 'white',
    textAlign: 'center',
  },
});

In essence, I am trying to utilize the aforementioned process to retrieve the coins inserted into the coinbox and apply them in a future scenario. Thank you all in advance for your assistance

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 host configuration issue while trying to use next/image in a TypeScript environment

I understand that when using Next.js image components without TypeScript, the URL must be configured in next.config.js, but I'm unsure why this doesn't work with TypeScript. ..., is not set up under images in your next.config.js. Learn more her ...

Creating an observable using a while loop: A step-by-step guide

I'm currently working on developing an Observable that actively queries an external service for updates and emits the new update when available: this._loop = new Rx.Observable<TDL.Result>(subscriber => { let shouldLoop = true; while ...

Incorporating numerous query parameters in Angular version 14

I am currently working on developing a multi-item filter feature for my application and I am faced with the challenge of sending multiple query parameters in the API request to retrieve filtered items. My main concern is whether there is a more efficient ...

Functions outside of the render method cannot access the props or state using this.props or this.state

Just starting out with react. I've encountered an issue where a prop used in a function outside the render is coming up as undefined, and trying to use it to set a state value isn't working either. I've researched this problem and found va ...

Obtain the precise Discriminated conditional unions type in the iterator function with Typescript

export type FILTER_META = | { type: 'string'; key: string; filters: { id: string; label?: string }[]; } | { type: 'time'; key: string; filters: { min: string; max: string }[]; } | { ...

Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeE ...

The table component in Primeng is encountering issues when being used with ngFor

I'm attempting to iterate through an array where each object represents a table in HTML, and it should be displayed like this: <p-table [value]="section" *ngFor="let section of sections"> <ng-template pTemplate="header"> <t ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

The UnFollow feature is currently unavailable on Stream IO for React Native

Incorporating Get Stream Io react native into my current project has been a great experience. You can check it out at https://github.com/GetStream/react-native-activity-feed One thing I've noticed is that while there's a feature in the library f ...

Executing a typescript class from a bash script: tips and tricks

Is it possible to invoke a TypeScript class and function from a bash script file? I have been unable to locate any relevant documentation on this topic. Below is the code snippet: TypeScript code: export class TestClass { constructor( public name ...

The automatic filtering feature does not kick in when the sorting is changed

I've been working on an app that features a video database, allowing users to filter videos by category and sort them by rating. https://i.sstatic.net/cESZT.png Currently, the filtering system works fine once the options are changed. However, there ...

Assigning different data types with matching keys - "Cannot assign type '...' to type 'never'."

I have a question regarding my application, where I am utilizing values that can either be static or functions returning those values. For TypeScript, I have defined the static values along with their types in the following manner: type Static = { key1: ...

What is the best way to display data retrieved through an HTTP service using ngFor?

I was attempting to inject a service (contact.service.ts) into a component (contact-list.component). The service contains data on employees defined in contacts.ts. While I was able to successfully receive the data, I encountered difficulty in rendering it ...

Enhance the functionality of a module by incorporating plugins when Typescript definitions are divided into multiple files

During my exploration of Typescript 2.2, I encountered a challenge in defining a module for HapiJS with various plugin options. To streamline the core code, I split it into multiple .d.ts files and then imported and re-exported them all from the index.d.t ...

How can I use Typescript to define a function that accepts a particular string as an argument and returns another specific string?

I've been working on this code snippet: const Locales = { en_gb: 'en-gb', en_us: 'en-us', } as const type ApiLocales = typeof Locales[keyof typeof Locales] type DatabaseLocales = keyof typeof Locales function databaseLanguage ...

Utilize generic types as object properties in TypeScript

Is there a way to achieve something similar in TypeScript like the following: export type CoordinateSelector = <T>(d: Coordinate) => d[T]; export interface LinkVerticalLineProps { x: CoordinateSelector<'x'>; y: CoordinateSele ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

How can you verify user identity in Firebase when making a call to a cloud function on a

I have integrated Firebase into my React Native app, and I have only enabled anonymous login feature. Currently, I am attempting to invoke a Cloud Function from the app without utilizing the firebase SDK. Instead, I intend to make the call using axios. De ...

Cease the inclusion of the definition file import in the output of TS

I am facing an issue with a third-party library that needs to be dynamically loaded with an authentication key. Since the API is complex, I require type definitions in my TypeScript code for better clarity. In my .tsconfig file, I have set "target": "esn ...

Issue encountered while trying to install react-native-gesture-handler using npm

Having an issue while running npm install react-native-gesture-handler. The terminal is throwing the following error: SAMETs-MBP:HelloWorld developer$ npm install react-native-gesture-handler npm ERR! path /Users/developer/HelloWorld/node_modules/react-na ...