import { errorApiRef , useApi } from '@backstage/core-plugin-api' ; import { useContext , useEffect } from 'react' ; import { AppContext , STORAGE_KEY } from './AppState' ; import { Settings } from './types' ; export function useSettings ( repoName ) { const [ settings , dispatch ] = useContext ( AppContext ) ; const errorApi = useApi ( errorApiRef ) ; useEffect ( ( ) => { const rehydrate = ( ) => { try { const stateFromStorage = JSON . parse ( localStorage . getItem ( `${ STORAGE_KEY }.${ repoName }` ) ! ) ; if ( stateFromStorage && Object . keys ( stateFromStorage ) . some ( k => ( settings as any ) [ k ] !== stateFromStorage [ k ] ) ) dispatch ( { type : 'setCredentials' , payload : stateFromStorage , } ) ; } catch ( error ) { errorApi . post ( error ) ; } } ; rehydrate ( ) ; } , [ dispatch , errorApi , settings , repoName ] ) ; const persist = ( state ) => { localStorage . setItem ( `${ STORAGE_KEY }.${ repoName }` , JSON . stringify ( state ) ) ; } ; return [ settings , { saveSettings : ( state ) => { persist ( state ) ; dispatch ( { type : 'setCredentials' , payload : state , } ) ; } , showSettings : ( ) => dispatch ( { type : 'showSettings' } ) , hideSettings : ( ) => dispatch ( { type : 'hideSettings' } ) , } , ] as const ; }