import React from 'react' ; import Logger from 'shared/libs/logger' ; const logger = Logger . create ( 'shared/hooks/useAttempt' ) ; export default function useAttemptNext ( status = '' as Attempt [ 'status' ] ) { const [ attempt , setAttempt ] = React . useState < Attempt > ( ( ) => ( { status , statusText : '' , } ) ) ; function handleError ( err ) { logger . error ( 'attempt' , err ) ; setAttempt ( { status : 'failed' , statusText : err . message } ) ; } function run ( fn ) { try { setAttempt ( { status : 'processing' } ) ; return fn ( ) . then ( ( ) => { setAttempt ( { status : 'success' } ) ; return true ; } ) . catch ( err => { handleError ( err ) ; return false ; } ) ; } catch ( err ) { handleError ( err ) ; return Promise . resolve ( false ) ; } } return { attempt , setAttempt , run , handleError } ; } export type Attempt = { status : 'processing' | 'failed' | 'success' | '' ; statusText ? : string ; } ; type Callback = ( fn ? : any ) => Promise < any > ; export type State = ReturnType < typeof useAttemptNext > ;