How to use setState with ssdp m-search discovery?

284 Views Asked by At

I am using SSDP search message to discover devices with connected same network but when i tried to call setState hooks inside client.on function I only get one device informations.

I initialized my state value in this way

const [deviceList, setDeviceList] = useState([]);

And create a function for the client to add deviceList as it is found

const getAllDevices = () => {

var Client = require('react-native-ssdp-remote').Client,
  client = new Client();

client.search('urn:dial-multiscreen-org:service:dial:1');

client.on('response', function (headers) {
  const url = new URL(headers.LOCATION);
  if (url != null) {
    if (!deviceList.includes(url)) {
      setDeviceList([...deviceList, url]);
    }
  }
});
};

and called this function inside useEffect

  useEffect(() => {
  getAllDevices();
  }, []);

There are 4 devices connected to same network and it goes into setDeviceList process 4 times but i can only get one device. Could you please support.

Thanks.

1

There are 1 best solutions below

1
Olgun Kaya On

I think this is more of a race condition instead of a library issue. Give it a try with using functional update on setDeviceList.

setDeviceList(deviceList => {
   return [...deviceList, url]
}