import { useState , useEffect } from 'react' ; import { i18n } from '@osd/i18n' ; import { CoreStart } from 'opensearch-dashboards/public' ; import { SavedQuery } from '../../../query' ; import { DataPublicPluginStart } from '../../..' ; import { populateStateFromSavedQuery } from './populate_state_from_saved_query' ; import { clearStateFromSavedQuery } from './clear_saved_query' ; interface UseSavedQueriesProps { queryService : DataPublicPluginStart [ 'query' ] ; notifications : CoreStart [ 'notifications' ] ; savedQueryId ? : string ; } interface UseSavedQueriesReturn { savedQuery ? : SavedQuery ; setSavedQuery : ( savedQuery : SavedQuery ) => void ; clearSavedQuery : ( ) => void ; } export const useSavedQuery = ( props ) : UseSavedQueriesReturn => { const [ savedQuery , setSavedQuery ] = useState < SavedQuery | undefined > ( ) ; useEffect ( ( ) => { const fetchSavedQuery = async ( savedQueryId ) => { try { const newSavedQuery = await props . queryService . savedQueries . getSavedQuery ( savedQueryId ) ; if ( newSavedQuery && newSavedQuery . id === savedQueryId ) { setSavedQuery ( newSavedQuery ) ; populateStateFromSavedQuery ( props . queryService , newSavedQuery ) ; } } catch ( error ) { setSavedQuery ( undefined ) ; clearStateFromSavedQuery ( props . queryService ) ; props . notifications . toasts . addWarning ( { title : i18n . translate ( 'data.search.unableToGetSavedQueryToastTitle' , { defaultMessage : 'Unable to load saved query {savedQueryId}' , values : { savedQueryId } , } ) , text : `${ error . message }` , } ) ; } } ; if ( props . savedQueryId ) fetchSavedQuery ( props . savedQueryId ) ; else setSavedQuery ( undefined ) ; } , [ props . notifications . toasts , props . queryService , props . queryService . savedQueries , props . savedQueryId , ] ) ; return { savedQuery , setSavedQuery : ( q ) => { setSavedQuery ( q ) ; populateStateFromSavedQuery ( props . queryService , q ) ; } , clearSavedQuery : ( ) => { setSavedQuery ( undefined ) ; clearStateFromSavedQuery ( props . queryService ) ; } , } ; } ;