Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6404

ConnectedDevice returns undefined

$
0
0

I'm trying to use the connectedDevice that has been initialised in a file which has the connecToDevice function, however when I try calling the connectedDevice in another file it's returned undefined. I've tried using a useEffect to re-rendend the component in which I want to use connectedDevice but it's still returns undefined.

//in this file I want to use connectedDevice but it returns undefinedfunction Info() {  const [device, setDevice] = useState<Device>();  const {connectedDevice} = useBLE();  useEffect(() => {    setDevice(connectedDevice!);  }, [connectedDevice]);  console.log(device?.id, 'is in info');    return (<View style = {{ backgroundColor: 'grey', height: '100%', flex: 1, padding: 5}}><ScrollView style = {{height: '85%', backgroundColor: 'white'}}>          {device? <Text>{device?.localName} is connected</Text>:<Text>Please Connect to a device</Text>}</ScrollView><View style = {{ backgroundColor: 'white', padding: 5, flexDirection: 'row', alignItems: 'center', position: 'relative', top:'1%'}}><TextInput style ={{borderWidth: 1, borderColor: '#ccc', borderRadius: 5, padding: 10, width: '80%'}} placeholder='Enter Command'></TextInput><TouchableOpacity style={{backgroundColor: '#007AFF', padding: 10, borderRadius: 5, marginLeft: 10}}>< Text style={{ color: 'blue', fontSize: 16}}>Send</Text></TouchableOpacity></View></View>    );}// This is the file where ConnectedDevice is declaredinterface BluetoothLowEnergyApi {  connectedDevice: Device | null;}function useBLE(): BluetoothLowEnergyApi {  const [connectedDevice, setConnectedDevice] = useState<Device | null>(null);  const connectToDevice = async (device: Device) => {    try {      setConnectedDevice(device);      const deviceConnection = await bleManager.connectToDevice(device.id);      await deviceConnection.discoverAllServicesAndCharacteristics();      bleManager.stopDeviceScan();      startStreamingData(deviceConnection);    } catch (e) {      console.log('FAILED TO CONNECT', e);    }  };console.log(connectedDevice?.id, 'Connected');// this is fine  return {    connectedDevice,  };}//This is the file where connecteToDevice was called and initialised the deviceconst renderItem = ({ item }: { item: Device }) => (<View style={{ margin: 10 }}><Text style={{ fontWeight: 'bold' }}>{item?.localName || 'Unknown'}</Text><Text>{item.id}</Text><Switch        onValueChange={(value) => {          if (value) {            connectToDevice(item);          } else{            disconnectFromDevice();          }        }}        value={connectedDevice != null}      /></View>  )

Viewing all articles
Browse latest Browse all 6404

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>