I'm a beginner with React and I am trying to call this API every 3 seconds to get the International Space Station coordinates and render them to the screen every call. So I fetch the API coordinates using setTimeout(), update the 'coords' state variable, and then use useEffect to update the ref 'coordRef' to those values, which I then pass to the child component, 'TomTomSearch', to use as well.
The problem is that when I run it in strict mode it makes many API calls and then eventually a never-ending stream of API calls, as seen by the multiple console logs during runtime, where as when I run it without the strict mode tags, it only calls it once per setTimeout() call. The API I'm using has a limit of 1 call/second and it always ends up giving me a 429 error eventually in strict mode.
145 FetchISS.js:21 fetched //(console logged 145 times in 15 seconds)
FetchISS.js:17
GET https://api.wheretheiss.at/v1/satellites/25544
429 (Too Many Requests)
I just need to know if this is just a side effect of using strict mode, or if I'm actually just doing this the wrong way. Also, any pointers or recommendations on any ugly code you see would be greatly appreciated!
function FetchISS() {
const [ coords, setCoords] = useState({lat: null, lon: null});
const coordRef = useRef({lat: null, lon: null});
useEffect(
() => {
coordRef.current = {lat: coords.lat, lon: coords.lon};
}
,[coords]);
function fetchISS() {
const iss_API = 'https://api.wheretheiss.at/v1/satellites/25544';
fetch(iss_API)
.then(results => results.json())
.then(results => {
setCoords({lat: results.latitude, lon: results.longitude});
console.log('fetched');
}).catch(err => {
console.log(err.message);
})
}
setTimeout(() => fetchISS(), 3000);
return(
<div>
{ coordRef.current.lat !== null && coordRef.current.lon !== null ?
<TomTomSearch coords={coords} /> : null }
</div>
)
}