I am currently working on incorporating a polling feature in React using TypeScript. This polling function is required to make a REST API call to retrieve a record from DynamoDB and then continue polling every 30 seconds until the 'Status' field in the record changes to 'Success'.
Here's the code snippet I attempted:
const poll = async function (fn: () => Promise<any>, fnCondition: (result: any) => boolean, ms: number): Promise<any> {
let result = await fn();
while (fnCondition(result)) {
await wait(ms);
result = await fn();
}
return result;
};
const wait = async function (ms = 1000): Promise<void> {
console.log('in wait function');
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
function callPolling(resJson: any): any {
try {
response = await fetch(url, {
method: 'POST',
body: JSON.stringify(request_data),
headers: { 'Content-Type': 'application/json' },
});
} catch (e: unknown) {
console.error(e);
}
return response;
}
const fetchRecord = callPolling(resJson);
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const validate = (result: { body: { Status: string } }) => result.body.Status === 'Success';
const responsePoll = await poll(fetchRecord, validate, 30000);
Upon testing, I noticed that the frontend application only manages to query DynamoDB once. Subsequent attempts to "poll" end up throwing a
Uncaught (in promise) TypeError: t is not a function
400 error. What could be causing this issue? Is my implementation of polling incorrect, or is there a more effective way to achieve this functionality?
As a newcomer to React and web application development, I have been following some blogs for guidance on implementing polling. Any insights or assistance in understanding my mistake would be greatly appreciated.