import React from 'react' ; import Logger from 'shared/libs/logger' ; const logger = Logger . create ( 'shared/hooks/useAttempt' ) ; const defaultState = { isProcessing : false , isFailed : false , isSuccess : false , message : '' , } ; export default function useAttempt ( initialState ) { const [ attempt , setState ] = React . useState ( ( ) => ( { ... defaultState , ... initialState , } ) ) ; const actions = React . useMemo ( ( ) => makeActions ( setState ) , [ setState ] ) ; return [ attempt , actions ] ; } function makeActions ( setState ) { function stop ( message = '' ) { setState ( { ... defaultState , isSuccess : true , message } ) ; } function start ( ) { setState ( { ... defaultState , isProcessing : true } ) ; } function clear ( ) { setState ( { ... defaultState } ) ; } function error ( err ) { logger . error ( 'attempt' , err ) ; setState ( { ... defaultState , isFailed : true , message : err . message } ) ; } function run ( fn ) { try { start ( ) ; return fn ( ) . then ( ( ) => { stop ( ) ; } ) . catch ( err => { error ( err ) ; throw err ; } ) ; } catch ( err ) { error ( err ) ; } } return { do : run , stop , start , clear , error , } ; } type State = typeof defaultState ; type Actions = { do : ( fn : Callback ) => Promise < any > ; stop : ( message ? : string ) => void ; start : ( ) => void ; clear : ( ) => void ; error : ( err : Error ) => void ; } ; type Callback = ( fn ? : any ) => Promise < any > ;