Created
July 11, 2022 19:24
-
-
Save nesbtesh/b7e7027dd900af34144eca34803e633c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import Bluelagoon from ".."; | |
import useConfirm from "../../hooks/useConfirm"; | |
import useNotification from "../../hooks/useNotification"; | |
import { useNotify } from "../../NotifyContext"; | |
function useBluelagoonPromise({ | |
method, | |
defaultData, | |
notifyError, | |
notifySuccess, | |
confirmText, | |
notifyReponseError, | |
defaultLoadingState, | |
defaultTimeout = 200, | |
}) { | |
const { notify, confirmCallback } = useNotify(); | |
const timer = React.useRef(); | |
const [response, setResponse] = React.useState({ ...defaultData }); | |
const [ | |
isLoading /* A state variable that is used to show a loading indicator. */, | |
setIsLoading, | |
] = React.useState(defaultLoadingState && true); | |
const [error, setError] = React.useState(null); | |
const handleSetLoaderFalse = (data) => { | |
const timeDiff = new Date() - timer.current; | |
setTimeout( | |
() => { | |
setResponse(data); | |
setIsLoading(false); | |
}, | |
defaultTimeout - timeDiff > 0 ? defaultTimeout - timeDiff : 0 | |
); | |
}; | |
const handleApiCall = React.useCallback( | |
(params) => { | |
timer.current = new Date(); | |
setIsLoading(true); | |
setError(null); | |
setResponse({ ...defaultData }); | |
return new Promise((resolve, reject) => { | |
Bluelagoon[method](params) | |
.then((resp) => { | |
if (resp) { | |
if (notifySuccess) { | |
notify({ | |
paragraph: notifySuccess, | |
info: true, | |
}); | |
} | |
handleSetLoaderFalse(resp); | |
resolve(resp); | |
} else { | |
handleSetLoaderFalse(defaultData); | |
throw new Error("server error"); | |
} | |
}) | |
.catch((err) => { | |
console.log(err); | |
if (notifyError || notifyReponseError) { | |
notify({ | |
paragraph: | |
notifyReponseError && err | |
? err.reason | |
: notifyError, | |
error: true, | |
}); | |
} | |
setError(err); | |
handleSetLoaderFalse(defaultData); | |
reject(err); | |
}); | |
}); | |
}, | |
[method, notifyError, notifySuccess, confirmText] | |
); | |
return { | |
wrappedApi: (params) => { | |
if (confirmText) { | |
confirmCallback({ | |
...confirmText, | |
callback: (confirm) => { | |
if (confirm) { | |
handleApiCall(params); | |
} else { | |
if (confirmText.callbackCancel) | |
confirmText.callbackCancel(); | |
} | |
}, | |
}); | |
} else { | |
return handleApiCall(params); | |
} | |
}, | |
isLoading, | |
error, | |
response, | |
}; | |
} | |
export default useBluelagoonPromise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment