useEffect(() => {
const interval = setInterval(() => {
backendAPIAxios.get(`/history${search}`)
.then((response: AxiosResponse<IHistoricPricesResponse>) => {
if (!response.data.success) {
return alert(`Failed to get historic prices with error: ${response.data.message}`)
}
sethistoricPricesState(() => response.data.data!);
})
.catch((e: AxiosError) => {
alert(`Failed to get historic prices with error: ${e}`)
})
}, 300000);
return () => clearInterval(interval);
}, [sethistoricPricesState]);
The broblem is that when I load the page first time I need to wait for the interval, how can I send the request for the first time and only then start it?
CodePudding user response:
All kinds of ways of doing this.
For instance, Why not simply export it to a seperate function and simply call it twice?
const fetchData = () => {
backendAPIAxios.get(`/history${search}`)
.then((response: AxiosResponse<IHistoricPricesResponse>) => {
if (!response.data.success) {
return alert(`Failed to get historic prices with error: ${response.data.message}`)
}
sethistoricPricesState(() => response.data.data!);
})
.catch((e: AxiosError) => {
alert(`Failed to get historic prices with error: ${e}`)
})
};
useEffect(() => {
fetchData();
const interval = setInterval(() => fetchData(), 300000);
return () => clearInterval(interval);
}, [sethistoricPricesState]);
Or you can transfer interval
to the component's scope,
(since you still need access to it in the cleanup function),
and set it in fetchData
instead.
Whatever you prefer and makes more sense to you.
CodePudding user response:
You can try something like this :-
const fetchAPIData = () => {
return backendAPIAxios
.get(`/history${search}`)
.then((response: AxiosResponse<IHistoricPricesResponse>) => {
if (!response.data.success) {
return alert(
`Failed to get historic prices with error: ${response.data.message}`
);
}
sethistoricPricesState(() => response.data.data!);
})
.catch((e: AxiosError) => {
alert(`Failed to get historic prices with error: ${e}`);
});
};
useEffect(async () => {
async function call() {
const res = await fetchAPIData();
//process res
}
call();
const interval = setInterval(() => {
call();
}, 300000);
return () => clearInterval(interval);
}, [sethistoricPricesState]);