question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Sometime i get double response messages

See original GitHub issue

I really really want to say thank you to you. I love your lib. It saves me in my project. But Sometimes I get double response messages. Could you take a look at my useBluetooth.js file and tell me where is my problem. I think I missed some clear subscription there. below are 2 files, or you can take a look via expo: https://snack.expo.dev/@hungdev/react-native-bluetooth-classic

Main File

import React, { useState, useRef, useEffect, useCallback } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Touchable } from 'react-native';
import styles from './styles/Home.Styles';
import useBluetooth from 'app/hooks/useBluetooth';
import RNBluetoothClassic from 'react-native-bluetooth-classic';

export default function Home() {

  const onReceivedDataScan = useCallback((data) => {
    console.tron.log('data?.data', data?.data); // ========> Get response here
    alert(data?.data);
  }, []);


  const { connection, setDevice, data, } = useBluetooth(onReceivedDataScan);

  useEffect(() => {
    getBondedDevices();
  }, []);

  const getBondedDevices = async () => {
    console.tron.log('-- GETTING BONDED DEVICES --');
    try {
      const listBondedDevices = await RNBluetoothClassic.getBondedDevices();
      const dv = listBondedDevices?.find(e => e.id === "F4:5E:AB:DB:1F:B9");
      setDevice(dv);
    } catch (err) {
      console.tron.log(err);
    }
  };



  return (
    <View style={styles.container}>
      
    </View>
  );
}

useBluethooth.js

import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import RNBluetoothClassic from 'react-native-bluetooth-classic';

export default function BluetoothClassic(onReceivedDataScan) {
  const [device, setDevice] = useState();
  const [data, setData] = useState([]);
  const [connection, setConnection] = useState(false);

  useEffect(() => {
    device && setTimeout(() => connect(), 0);
  }, [device]);

  const addData = (message) => setData(prev => [message, ...prev]);

  const connect = async () => {
    try {
      let connection = await device.isConnected();
      if (!connection) {
        addData({
          data: `Attempting connection to ${device.address}`,
          timestamp: new Date(),
          type: 'error',
        });

        connection = await device.connect();

        addData({
          data: 'Connection successful',
          timestamp: new Date(),
          type: 'info',
        });
      } else {
        addData({
          data: `Connected to ${device.address}`,
          timestamp: new Date(),
          type: 'error',
        });
      }

      setConnection(connection);
      initializeRead();
    } catch (error) {
      addData({
        data: `Connection failed: ${error.message}`,
        timestamp: new Date(),
        type: 'error',
      });
    }
  };

  const disconnect = async (disconnected) => {
    console.tron.log('disconnected', disconnected);
    connect();
    try {
      if (!disconnected) {
        disconnected = await device.disconnect();
      }

      addData({
        data: 'Disconnected',
        timestamp: new Date(),
        type: 'info',
      });

      setConnection(!disconnected);
    } catch (error) {
      addData({
        data: `Disconnect failed: ${error.message}`,
        timestamp: new Date(),
        type: 'error',
      });
    }

    // Clear the reads, so that they don't get duplicated
    uninitializeRead();
  };



  const initializeRead = () => {
    disconnectSubscription = RNBluetoothClassic.onDeviceDisconnected(() => disconnect(true));

    readSubscription = device.onDataReceived(data => onReceivedData(data));
  };

  /**
 * Clear the reading functionality.
 */
  const uninitializeRead = () => {
    if (readInterval) {
      clearInterval(readInterval);
    }
    if (readSubscription) {
      readSubscription.remove();
    }
  };

  const onReceivedData = (event) => {
    event.timestamp = new Date();
    const dataReceived = {
      ...event,
      timestamp: new Date(),
      type: 'receive',
    };
    addData(dataReceived);
    onReceivedDataScan?.(dataReceived);
  };



  return { connect, disconnect, connection, setDevice, data, uninitializeRead };
}

Thank you!

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
kenjdavidsoncommented, Jan 19, 2022

If you go through some of the closed issues, you can see some of their comments.

Your code looks ok, nothing really jumps out with regards to removing the subscription. So this is really the only thing that I can think of - the hot reload.

0reactions
hungdevcommented, Jan 20, 2022

Thank you for your support ❤️. I will close this issue to avoid distracting issues and discussions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why Is My Phone Sending Double Texts: Answers & Fixes
Sometimes the phone doesn't realize the text actually went through, so the phone will send a second copy as a result.
Read more >
Whoa. Double texting might actually get your matches to ...
Double texting might actually get your matches to respond. It may seem desperate, but it works. On the surface, sending multiple messages on...
Read more >
Why did the person I sent a message to get duplicate ...
If you find duplicate messages sent within a few seconds of each other. This means that Twilio sent multiple messages to the carrier,...
Read more >
Double-Texting Isn't Always Bad Idea, According to a Therapist.
Double -texting is seen as taboo in modern dating, but a therapist says context and content will decide whether it's appropriate or not....
Read more >
6 Tips On How To Make Double Texting A Success
If someone texts you more than one message in a row without waiting, it's not a double text. The time between texts is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found