import { Dispatch , useEffect , useState } from 'react' ; import type { CreateExceptionListItemSchema , PersistHookProps , UpdateExceptionListItemSchema , } from '@kbn/securitysolution-io-ts-list-types' ; import { addExceptionListItem , updateExceptionListItem } from '@kbn/securitysolution-list-api' ; import { transformNewItemOutput , transformOutput } from '../transforms' ; interface PersistReturnExceptionItem { isLoading : boolean ; isSaved : boolean ; } export type ReturnPersistExceptionItem = [ PersistReturnExceptionItem , Dispatch < CreateExceptionListItemSchema | UpdateExceptionListItemSchema | null > ] ; param http param onError export const usePersistExceptionItem = ( { http , onError , } ) : ReturnPersistExceptionItem => { const [ exceptionListItem , setExceptionItem ] = useState < CreateExceptionListItemSchema | UpdateExceptionListItemSchema | null > ( null ) ; const [ isSaved , setIsSaved ] = useState ( false ) ; const [ isLoading , setIsLoading ] = useState ( false ) ; const isUpdateExceptionItem = ( item ) : item is UpdateExceptionListItemSchema => Boolean ( item && ( item as UpdateExceptionListItemSchema ) . id != null ) ; useEffect ( ( ) => { let isSubscribed = true ; const abortCtrl = new AbortController ( ) ; setIsSaved ( false ) ; const saveExceptionItem = async ( ) : Promise < void > => { if ( exceptionListItem != null ) { try { setIsLoading ( true ) ; if ( isUpdateExceptionItem ( exceptionListItem ) ) { const transformedList = transformOutput ( exceptionListItem ) ; await updateExceptionListItem ( { http , listItem : transformedList , signal : abortCtrl . signal , } ) ; } else { const transformedList = transformNewItemOutput ( exceptionListItem ) ; await addExceptionListItem ( { http , listItem : transformedList , signal : abortCtrl . signal , } ) ; } if ( isSubscribed ) { setIsSaved ( true ) ; } } catch ( error ) { if ( isSubscribed ) { onError ( error ) ; } } if ( isSubscribed ) { setIsLoading ( false ) ; } } } ; saveExceptionItem ( ) ; return ( ) : void => { isSubscribed = false ; abortCtrl . abort ( ) ; } ; } , [ http , exceptionListItem , onError ] ) ; return [ { isLoading , isSaved } , setExceptionItem ] ; } ;