import { ReactNode , useCallback , useContext } from 'react' ; import { ACTIONS } from '../state/constants' ; import { PortalDispatchContext } from '../contexts/portal' ; export const usePortal = ( hostName = 'root' ) => { const dispatch = useContext ( PortalDispatchContext ) ; if ( dispatch === null ) { throw new Error ( "'PortalDispatchContext' cannot be null, please add 'PortalProvider' to the root component." ) ; } const registerHost = useCallback ( ( ) => { dispatch ( { type : ACTIONS . REGISTER_HOST , hostName : hostName , } ) ; } , [ ] ) ; const deregisterHost = useCallback ( ( ) => { dispatch ( { type : ACTIONS . DEREGISTER_HOST , hostName : hostName , } ) ; } , [ ] ) ; const addUpdatePortal = useCallback ( ( name , node ) => { dispatch ( { type : ACTIONS . ADD_UPDATE_PORTAL , hostName , portalName : name , node , } ) ; } , [ ] ) ; const removePortal = useCallback ( ( name ) => { dispatch ( { type : ACTIONS . REMOVE_PORTAL , hostName , portalName : name , } ) ; } , [ ] ) ; return { registerHost , deregisterHost , addPortal : addUpdatePortal , updatePortal : addUpdatePortal , removePortal , } ; } ;