reactjsreact-nativebluetoothreact-native-ble-plx

React Native - Global Event Listener


I have a listener registered in my Pairing screen that calls a method whenever the connected Bluetooth device gets disconnected

// Pairing.js

const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);

componentDidMount() {
  this.handlerDisconnected = bleManagerEmitter.addListener(
    "BleManagerDisconnectPeripheral",
    this.handlePeripheralDisconnected
  );
}

componentWillUnmount() {
  this.handlerDisconnected.remove();
}

I want this event all across my app, how can I create a global event listener and not have to copy paste this code across every screen?

p.s I am using react-native-ble-manager and redux+sagas if that helps


Solution

  • Add the listener in your top level component (App.js)