|
| 1 | +import { noop } from 'lodash' |
| 2 | +import { MutableRefObject, useEffect, useRef } from 'react' |
| 3 | +import { NavigateFunction, useLocation, useNavigate } from 'react-router-dom' |
| 4 | + |
| 5 | +import { |
| 6 | + LearnUserCertificationProgress, |
| 7 | + userCertificationProgressCompleteCourseAsync, |
| 8 | + UserCertificationProgressStatus, |
| 9 | +} from '../../learn-lib' |
| 10 | +import { getCertificationCompletedPath } from '../../learn.routes' |
| 11 | + |
| 12 | +export const useCheckAndMarkCourseCompleted: ( |
| 13 | + isLoggedIn: boolean, |
| 14 | + providerName: string, |
| 15 | + certificateProgress?: LearnUserCertificationProgress, |
| 16 | + userHandle?: string, |
| 17 | + setCertificateProgress?: (progess: LearnUserCertificationProgress) => void |
| 18 | +) => void = (isLoggedIn, providerName, certificateProgress, userHandle, setCertificateProgress = noop) => { |
| 19 | + const navigate: NavigateFunction = useNavigate() |
| 20 | + const location: any = useLocation() |
| 21 | + const isUpdating: MutableRefObject<boolean> = useRef(false) |
| 22 | + |
| 23 | + useEffect(() => { |
| 24 | + // if we don't yet have the user's handle, |
| 25 | + // or if the cert isn't complete, |
| 26 | + // or the cert isn't in progress, |
| 27 | + // there's nothing to do |
| 28 | + if ( |
| 29 | + isUpdating.current |
| 30 | + || !isLoggedIn |
| 31 | + || certificateProgress?.certificationProgressPercentage !== 100 |
| 32 | + || certificateProgress?.status !== UserCertificationProgressStatus.inProgress |
| 33 | + ) { |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + // Prevent further calls to the backend until this one is completed |
| 38 | + isUpdating.current = true |
| 39 | + // it's safe to complete the course |
| 40 | + userCertificationProgressCompleteCourseAsync( |
| 41 | + certificateProgress?.id, |
| 42 | + certificateProgress.certification, |
| 43 | + userHandle as string, |
| 44 | + providerName, |
| 45 | + ) |
| 46 | + .then(setCertificateProgress) |
| 47 | + .then(() => { |
| 48 | + const completedPath: string = getCertificationCompletedPath( |
| 49 | + providerName, |
| 50 | + certificateProgress.certification, |
| 51 | + ) |
| 52 | + isUpdating.current = false |
| 53 | + navigate(completedPath, { |
| 54 | + state: { |
| 55 | + tcaCertInfo: location.state?.tcaCertInfo, |
| 56 | + }, |
| 57 | + }) |
| 58 | + }) |
| 59 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 60 | + }, [ |
| 61 | + certificateProgress, |
| 62 | + isLoggedIn, |
| 63 | + userHandle, |
| 64 | + providerName, |
| 65 | + location.state, |
| 66 | + ]) |
| 67 | +} |
0 commit comments