0

I'm making a bluetooth remote in React Native. I have a class BLE that works on it's own, but parts of it don't work when I it in another class.

import BLE from './Core/BLE.js'

const myBLE = new BLE();

function DebugScreen(){
    useEffect(() => {
      myBLE.componentDidMount();
    }, []);
    
    return(
      <ScrollView>
        <Text>State: {myBLE.state.info}</Text>
        <Text>Devices: {JSON.stringify(myBLE.state.ble_devices)}</Text>
      </ScrollView>
    )
  }
  
export default DebugScreen;

The devices text box shows data just fine, but state does not. I verified that this was not simply the state not refreshing by putting a timer on the screen.

My question is, is there a fundamental difference between code running in an instantiated class and one that isn't?

  • Are you trying to run react component as a normal class instead of using it as intended? – Konrad Sep 30 '22 at 22:26
  • The view won‘t update when myBLE properties were changing. For testing try to use a force update with setInterval to refresh the view manually https://stackoverflow.com/questions/53215285/how-can-i-force-a-component-to-re-render-with-hooks-in-react – Michael Bahl Oct 01 '22 at 09:11
  • @MichaelBahl I put a timer in like this: const [time, setTime] = useState(Date.now()); useEffect(() => { myBLE.componentDidMount(); const interval = setInterval(() => setTime(Date.now()), 1000); return () => { clearInterval(interval); }; }, []); It still only shows the ble_devices, but at least they are refreshing now. – Ethan Stacey Oct 03 '22 at 20:47

1 Answers1

0

I figured out what I was doing wrong. Instantiating classes the normal JS way is bad practice in React/React Native. To have top level code and information, I need to use context https://reactjs.org/docs/context.html

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 17 '22 at 22:22