-1

I am trying to create a bluetooth app in react native. To raise the challenge i decided to create my own native bluetooth module. Now i want to render some status data about the bluetooth connection ( if it is enabled or connected to any device).

I have a function that calls a function Bluetooth.isEnabled(). Bluetooth.isEnabled has a callback argument that will get the status of the bluetooth (true it is enabled or false otherwise).

 bluetooth_isEnabled(){
   
    Bluetooth.isEnabled((status)=>{
      console.log(status)
      return status;
      

    })
  

Here is the constructor function

class App extends Component {
  constructor(props){

    super(props)
    
    this.state = {
    
      isConnected: false,
      isEnabled: false 
    }
    this.checkConnection = this.checkConnection.bind(this);
    this.bluetooth_isEnabled = this.bluetooth_isEnabled.bind(this);
    this.bluetoothStatus = this.bluetoothStatus.bind(this);
  }
.
.
.

In the following function i am trying to check if the bluetooth is enabled or not but status is undefined

bluetoothStatus(){
    var status = this.bluetooth_isEnabled()
    console.log(status)
    if(this.bluetooth_isEnabled()){
      return(
        <Text>ENABLED</Text>
      )
    }
    else{
      return(
        <Text>DISABLED</Text>
      )
    }
    
  }

bluetooth_isEnabled() will always return undefined. I checked that consoled.log the status in Bluetooth.isEnabled() function and it is true.

Why does bluetooth_isEnabled() return undefined?

Stefan Denis
  • 3
  • 1
  • 4

1 Answers1

1

Your bluetooth_isEnabled function is an asynchoronous function. You should use promises or async/await structure to return a value. Update your function to return a promise using async/await

 bluetooth_isEnabled = async()=>{

   const status = await Bluetooth.isEnabled();      

})

Then use it as :

this.bluetooth_isEnabled.then((status) => {
   this.setState({status:status})
})

And you should not access variables with this.variable_name and use state instead.

bluetoothStatus(){
 var status = this.state.status;
 console.log(status)
 if(status()){
  return(
    <Text>ENABLED</Text>
  )
}
else{
  return(
    <Text>DISABLED</Text>
  )
 }
}
Çağatay Sel
  • 801
  • 7
  • 14