I have a functional React component that, among other things, sets up a Bluetooth connection and sets a device variable. It also sets up a callback listener for when Bluetooth responses come in. The listener needs to access device.
export default function App() {
const [device, setDevice]... ?
var deviceVar;
const listener = (data) => {
// needs device
console.log(device, deviceVar);
// 'device' is undefined but 'deviceVar' is correct
}
const scan = () => {
setDevice(...);
device = ...
addListener(listener)
}
}
Using setState is unreliable because the listener is triggered before (i.e.) device was updated.
What is the correct way to handle this? Is there a more functional/hooks approach?
Note that this question is NOT about using useEffect to provide my own callback on device. It is about an 'external' callback that I can't control the timing of.
addListeneris implemented? Also,device = ...would be an anti-pattern, as you should be usingsetDeviceinstead.device = ...is an anti-pattern, this is what I'm trying to fix