Have some confusion in using the react state, as from my code below, when trying to hit the API, the res2 will be running twice, and res3 will be running 4 times, and so on going deeper on the nested if.
Is there any way to only hit each one of the API chains once, then after hitting each API would update the taskNum state and render it on screen?
function Loading() {
const [taskNum, setTaskNum] = useState(1);
const location = useLocation();
const client = axios.create({
baseURL: "https://localhost:8000"
});
const predictImage = useCallback(async () => {
try {
const res1 = await client.post(`/get-box/${location.state.id}`);
if (res1 && !(res1["data"]["img_id"] === -1)) {
setTaskNum(2);
const res2 = await client.post(
`/get-img/${res1["data"]["img_id"]}`
);
console.log("response 2");
if (res2) {
setTaskNum(3);
const res3 = await client.post(
`/super/${res2["data"]["historyId"]}`
);
console.log("response 3");
if (res3) {
setTaskNum(4);
const res4 = await client.post(
`/easy/${res3["data"]["historyId"]}`
);
console.log("response 4");
if (res4) {
setTaskNum(5);
const res5 = await client.post(
`/get-history/${res4["data"]["historyId"]}`
);
console.log("response 5");
if (res5) navigate("/hasil", { state: res5["data"] });
}
}
}
}
} catch (error) {
console.log(error);
setTaskNum(0);
}
}, []);
useEffect(() => {
predictImage();
}, []);
get description function
const getDescription = (num) => {
if (num === -1) {
return "Oh no...";
}
if (num === 1) {
return "Done Uplo...";
}
if (num === 2) {
return "Found the..";
}
if (num === 3) {
return "Plates are ready....";
}
if (num === 4) {
return "Eureka..";
}
if (num === 5) {
return "All Done..";
}
return "I'm sorry but..";
};
my render return
return (
<div className="container mx-auto mt-16 mb-24">
<div className="flex flex-col items-center mt-16">
<ScaleLoader
color="#3F83F8"
height={30}
speedMultiplier={0.8}
width={8}
/>
<div className="mt-6 text-xl font-medium">Doing Some Magic!</div>
<span className="mt-1 text-center font-medium text-gray-500">
{taskNum}/5 Task
<br /> {getDescription(taskNum)}
</span>
</div>
</div>
);
}
I've been trying to nest the setTaskNum on conditional if and function to handle updates, but all of them always hit the API multiple times.
if (res1 && !(res1["data"]["userId"] === -1)) {
if (taskNum === 1) {
console.log("setTaskNum(2)");
setTaskNum(2);
}
const res2 = await client.get(`/users/${res1["data"]["userId"]}`);
console.log("response 2");
EDIT My real API has a long processing time, it is Machine Learning related (inference image)
Live preview of the error see in console



res1,res2, etc are response values, can you clarify what you mean by "running"? What are the steps to reproduce?