import { useEffect , useState } from 'react' ; import useAttempt from 'shared/hooks/useAttemptNext' ; import TeleportContext from 'teleport/teleportContext' ; import { Resource , KindRole } from 'teleport/services/resources' ; export default function useRoles ( ctx ) { const [ items , setItems ] = useState < Resource < KindRole > [ ] > ( [ ] ) ; const { attempt , run } = useAttempt ( 'processing' ) ; function fetchData ( ) { return ctx . resourceService . fetchRoles ( ) . then ( received => { setItems ( received ) ; } ) ; } function save ( yaml , isNew ) { if ( isNew ) { return ctx . resourceService . createRole ( yaml ) . then ( result => { setItems ( [ result , ... items ] ) ; } ) ; } return ctx . resourceService . updateRole ( yaml ) . then ( result => { setItems ( [ result , ... items . filter ( r => r . name !== result . name ) ] ) ; } ) ; } function remove ( name ) { return ctx . resourceService . deleteRole ( name ) . then ( ( ) => { setItems ( items . filter ( r => r . name !== name ) ) ; } ) ; } useEffect ( ( ) => { run ( ( ) => fetchData ( ) ) ; } , [ ] ) ; return { items , attempt , save , remove , } ; } export type State = ReturnType < typeof useRoles > ;