简体   繁体   中英

How to add only new items to array ReactNative

I'm working with Bluetooth in my ReactNative app. I'm trying to create UI for discovered devices. For working with BT I use library react-native-ble-plx and method:

startDeviceScan(
      UUIDs: UUID[] | null,
      options: ScanOptions | null,
      listener: (error: BleError | null, scannedDevice: Device | null) => void
    ): void

and I use array in such way:

export default class App extends Component {
  state = {
    devices: [],
  };
....

}

and add item to array of devices:

BleManager.startDeviceScan(
          null,
          {
            allowDuplicates: false,
          },
          async (error, device) => {
            if (error) {
              console.log(error.reason);
              _BleManager.stopDeviceScan();
            }
            if (device.localName != null) {
              if (!this.state.devices.includes(device)) {
                this.state.devices.push(device);
              }
            }
          },
        );

but here I see that my check includes does not work and check that item is in array does not help. How I can check that I already have some items in the array, or it can be done in another way?

device is object and devices is your array of objects, you can not check if devices array contains device object or not with includes method. You can check with this function as shown below.

const isDeviceInclude = (device) => {
  if (this.state.devices.filter(e => e.id === device.id).length > 0) {
    return true;
  }
  else {
    return false;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM