I am implementing an SSDP device discovery app using react-native and react-native-ssdp library. Basically what I am doing is;
Multicasting to network for ssdp devices and listing them on my screen. In order to do the listing;
I have a function that registers on ssdp responses. Each time a response from a device received we are updating the state like setDeviceList([...deviceList, newDevice]);
But since the devices respond so quick (less than a half of a second), race condition happens and then the update missing real list. In this case I can only see the last device responding in the list.
How can I fix this ?
I assume you have used useState
for the deviceList.
The set-Method of an useState can take a direct parameter or a function where the input parameter is the current value of the state. So you can try something like this:
const [deviceList, setDeviceList] = useState([])
...
setDeviceList((currentDeviceList) => [...currentDeviceList, newDevice])
Alternatively use something like redux and dispatch every single device to the store. These messages will be queued and you should avoid race conditions.