I have a list of detected Bluetooth devices, deviceList, that is setup with useState:
const [deviceList, setDeviceList] = useState([]);
I have a button that initiates device scans. I need the device list to be reset to [] every time a scan starts. I do:
const scanForDevices = () => {
setDeviceList([]);
manager.startDeviceScan(null, null, (error, device) => {
// add device to device list
setDeviceList(old => [...old, device]);
}
}
The problem is that setDeviceList is not synchronous, and deviceList is not reset by the time the new device is supposed to be added. This can result in duplicate devices. I can prevent duplicates by filtering, but that's just a hack on the actual problem.
I cannot use useEffect to solve this problem so please do not suggest it. startDeviceScan cannot be run every time deviceList changes.
How are situations like this solved in the absence of truly atomic setState?