Javascript communication between a React component and a js library

416 views Asked by At

I have been working on a Bluetooth based KaiOS mobile application in which the user interfaces have developed using React.js and I had created a simple javascript class to manage the Bluetooth based operations such as scanning, connect/disconnect, data transfer, etc. I have been trying to send data or object to the react component from the Blemanager.js class when the devices are scanned.

The following code has been used to check for a device with a particular address and if found, resolve the promise so that the object has been sent to the React component. Now, I do want to send the scanned devices object to the react component and check the notified device object is the required one, and stop scanning. How this can be achieved in Javascript.

I am an iOS developer and with respect to iOS, I am looking for a delegation or observable pattern.

startLeScan = () => {
    return new Promise((resolve, reject) => {
      navigator.mozBluetooth.defaultAdapter.startLeScan([])
      .then(function(handlerLE) {
        handlerLE.ondevicefound = function(eventLE) {
          if (eventLE.device.address === "ed:ec:90:87:5d:86") {
            navigator.mozBluetooth.defaultAdapter.stopLeScan(eventLE.target);
            console.log('FOUND:', 'Address:', eventLE.device.address, 'Name:', eventLE.device.name, 'Type:', eventLE.device.type);

            resolve({"eventLE":eventLE})
          }
        }
      })
      .catch(function(e) {
        console.log(e);
        reject({error: e })
      });
    })
  }
2

There are 2 answers

1
Phil On

I would refer to this documentation on the Bluetooth spec including good examples on how to use it.

https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web

There is a characteristics object onto which you can attach event handlers. These can in turn fire your class methods as pleased.

Also there is an onDisconnected method that can also fire your methods.

3
kirecligol On

Assuming you use redux in your application, communication between a utility class and component class can be done by passing down the store object to the utility class.

  1. create a utility class, non-component.
import { bindActionCreators } from 'redux';
import { setBluetoothAddresses } from './some-action-file';

class BluetoothUtility {
  constructor(store) {
    this.actions = bindActionCreators(
      { setBluetoothAddresses },
      store.dispatch
    )
  }

  startLeScan = () => {
     // on promise done => call this.actions.setBluetoothAddresses with resolved value
  }
}

let instance;
export const initBluetoothUtility = (store) => {
  if (!instance) {
    instance = new BluetoothUtility(store);
  }
}
  1. in root component, where you use redux provider
class App {
   componentDidMount() {
     initBluetoothUtility(store);
   }
}
  1. then in the component you can use the value from redux store