live.js
const [report, setReport] = useState([]);
const [result, setResult] = useState([]);
useEffect(() => {
pose.onResults(onResults); => pose runs every second which runs onResults function every second
}, []);
const onResults = async () => {
setResult(results.poseLandmarks); ==> It set above state name result
};
useEffect(() => {
updateReport(); ==> as result state update this runs function updateReport
}, [result]);
const updateReport = async (result) => {
let reportData = [...report];
let updatedReport = [];
let saveReport = [];
if (report.length > 99) {
saveReport = reportData.slice(0, 100);
let body = {
room_id: roomId,
formatReport: {
"frames": saveReport
},
session: sessionId
};
reportData.splice(0, 100);
await awsUpload(body.formatReport, body.room_id); ==> This function uploads file to aws
}
reportData.push(updatedReport);
setReport(reportData); ===> It set in report state
}
onResult is running at each second I want once updateReport function runs it must complete all its execution before running again but before completing execution it runs again as result state which is dependency is updating at each second
You could introduce a flag to track wether updateReport is currently already running:
const [isUpdatingReport, setIsUpdatingReport] = useState(false);
And then in onResult only call updateReport if it's not currently running:
const onResults = async () => {
setResult(results.poseLandmarks);
if (!isUpdatingReport) {
setIsUpdatingReport(true);
updateReport();
}
};
In addition, at the end of all the async stuff in updateReport, make sure to signal that the work is done with
const updateReport = async (result) => {
// ...
setIsUpdatingReport(false);
};
This way there will only be one report being updated at the same time.
Some other thoughts on your code:
updateReport has one argument (result) in your snippet but gets called without arguments. Maybe something missing?result to be a state variable? It seems that its only purpose is to be processed by updateReport. If that is true you could simply pass it to the function. But maybe it gets rendered in the component, don't know.