The use of useState and useEffect hooks in the IDVerificationContextProvider and VerificationContextProvider that were unnecessary was triggering many extra re-renders and inappropriate renders, causing a UI flicker across multiple re-renders.
32 lines
927 B
JavaScript
32 lines
927 B
JavaScript
import { useEffect, useState } from 'react';
|
|
|
|
import {
|
|
IDLE_STATUS, LOADING_STATUS, SUCCESS_STATUS, FAILURE_STATUS,
|
|
} from './constants';
|
|
|
|
// eslint-disable-next-line import/prefer-default-export
|
|
export function useAsyncCall(asyncFunc) {
|
|
// React doesn't batch setStates call in async useEffect hooks,
|
|
// so we use a combined object here to ensure that users
|
|
// re-render once.
|
|
const [data, setData] = useState({ status: IDLE_STATUS });
|
|
|
|
useEffect(
|
|
() => {
|
|
(async () => {
|
|
setData(currData => ({ ...currData, status: LOADING_STATUS }));
|
|
const response = await asyncFunc();
|
|
|
|
if (Object.keys(response).length === 0) {
|
|
setData(currData => ({ ...currData, status: FAILURE_STATUS, data: response }));
|
|
} else {
|
|
setData(currData => ({ ...currData, status: SUCCESS_STATUS, data: response }));
|
|
}
|
|
})();
|
|
},
|
|
[asyncFunc],
|
|
);
|
|
|
|
return data;
|
|
}
|