im trying to fetch data to my react app. What is the best solution to fetch data every second? I have it in setInterval, which is probably not the best 🙂 Because of it, if the requests are still pending, because of slow connection for example, then I have like tens of pending requests in network in dev tools. Here is my code.
const [dataRigs, setDataRigs] = useState<[]>([]);
const [dataGames, setDataGames] = useState<[]>([]);
const [dataMeta, setDataMeta] = useState<MetaType>({});
const getStaticData = async () => {
const metadata = await fetch(process.env.REACT_APP_API_URL + '/Enumerations/venue-metadata');
const metaJson = await metadata.json();
setDataMeta(metaJson);
}
const getRefreshedData = async () => {
const rigs = await fetch(process.env.REACT_APP_API_URL + '/Rigs');
const games = await fetch(process.env.REACT_APP_API_URL + '/GroupSessions');
const rigsJson = await rigs.json();
const gamesJson = await games.json();
setDataRigs(rigsJson);
setDataGames(gamesJson);
}
useEffect(() => {
getStaticData();
}, []);
useEffect(() => {
let interval = setInterval(() => getRefreshedData(), (1000))
//destroy interval on unmount
return () => clearInterval(interval)
}, []); `
I tried to do something like a gettingRefresh variable, which in each iteration of setInterval function, but it did not work 🙁
2
Answers
You could add a simple "semaphore" to avoid new requests before the current one is over.
Note the
finally
, which guarantees to reset the flag "no matter what".That fits, however it is not the best solution if you need a tight polling. That is, the flag only prevents to send a request, but the new one it comes when the timer ticks. If you need a more responsive request, you should use
setTimeout
instead ofsetInterval
. However, that requires a different approach.If you have control over the server, you probably want to use a websocket for this and let the server tell the client when something changed vs. the opposite. Assuming you don’t, the best solution is probably not to check every second, but to check 1 second after the last request succeeded.
Here’s an example snippet: