chrisrzhou / react-globe

Create beautiful and interactive React + ThreeJS globe visualizations with ease.
https://react-globe.netlify.app/
MIT License
308 stars 54 forks source link

Markers not updated via React Hooks #49

Open r1beguin opened 3 years ago

r1beguin commented 3 years ago

I am trying to track satellite position around the globe in "almost" real time via TLE data. I am using React hooks to initialize the marker state, and a useEffect to update the marker state. However, while I can monitor that the coordinates of the markers are indeed changing, the rendered position on the globe is not moving. I have to reload the whole page to have the marker move.

`

const [markers, setMarkers] = React.useState([]);
const [refresh, setRefresh] = React.useState(true);
const [globe, setGlobe] = React.useState(null);
const options = {
    globeGlowColor: "#292929",
    enableGlobeGlow: false,
    markerTooltipRenderer: marker => `${marker.name}`,
  };

React.useEffect(() => {
    if (refresh === true){
        fetch(starlink)
        .then((r) => r.text())
        .then(text  => {
            const lines = text.match(/(?:.+\n?)/g, '');
            var i,j,temparray,chunk = 3;
            const stringArray= []
                for (i=0,j=lines.length; i<j; i+=chunk) {
                    temparray = lines.slice(i,i+chunk);
                    stringArray.push(temparray)                 
        }

        const marks= []
        stringArray.map((sat, i) => {

            const name = getSatelliteName(sat);
            const latLonObj = getLatLngObj(sat);

            marks.push({
                id: i,
                name: name,
                city: 'Starlink',
                color: "red",
                value: 35,
                coordinates: [latLonObj.lat, latLonObj.lng]
            })

            return 1
        })

        setMarkers(marks);

        globe && globe.updateMarkers(marks);
        globe && globe.updateMarkers(markers)
        })
        setRefresh(false)
    }

}, [refresh])
return (

            <ReactGlobe onGetGlobe={setGlobe} height="80%" markers={markers} options={options} 
globeBackgroundTexture={null}/>
<Button onClick={() => setRefresh(true)} />
)
}

`

tgmof commented 3 years ago

Hey Buddy! I think it is more a question for StackOverflow than here. But you probably already figured out the issue and forget to close this issue? I see 2 issues in your code:

  1. It doesn't compile since your return expression should be linted with "JSX expressions must have one parent element."
  2. You added these 2 lines globe && globe.updateMarkers(marks);globe && globe.updateMarkers(markers) that are probably conflicting with the state since the setMarkers is executed asynchronously whereas your globe.updateMarkers calls are executed synchronously. Does it work if you delete these 2 lines?