You have the following in
You should not call
useEffect. You should just return it, like this:
You’re also calling
getLevel in multiple places, but
getLevel sets up the subscription to the battery level notifications. You should only call it once (and rather with a name like
useEffect. Then whenever you want to reference the current battery level you should use the
level variable. The
level variable will be updated by the
setLevel(batteryLevel) call on line 36.
I think it would also be better not to mix up the code for the “alarm” (which I’d rather call an “alert” or a “threshold”) with the code that subscribes to the battery level.
I think it would be easier to figure out what’s going on if you first get it working without the “alarm” stuff. Once you’ve got that working, try adding in the other stuff piece by piece. Then if something stops working as you expect it will be easier to figure out what went wrong.
If you really want to re-subscribe to the battery level changes when the “alarm” level changes you should put
useEffect's dependency array.
Another issue (also with my code) is that we should use
useRef for the subscription.