'Update device position and send to server React Hook

I'm fairly new to React JS and all the web dev things. I'm trying to create an application that can get the position of the devices, using geolocation.watchPosition, and once the new position has been retrieved, I send it to the server. What I have so far

const [center, setCenter] = useState<google.maps.LatLngLiteral>({
        lng: 20, //some random number for lng and lat
        lat: 20
    });

//Just here for context, doesn't necessarily have to be inside the component
const socket = new WebSocket("ws://localhost:12345/websocket");

useEffect( () => {
    if (navigator.geolocation) {
            navigator.geolocation.watchPosition((e:GeolocationPosition) => {
                const { latitude, longitude } = e.coords;
                //Tried to put the sending location to server code here
                setCenter({ lat: latitude, lng: longitude });
            })
        }
})
useEffect(() => {
        socket.onopen = (e) =>{
            console.log("CONNECTED")
        }
        socket.onmessage = (e) => {
            console.log(e)
        }
    })

Right now I think I can get the coordinates whenever device's location changes. However, where should I put the sending location to server code? I tried to put it right above setCenter but it infinitely sending the data to server



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source