import { useCallback } from 'react' ; import { useDispatch } from 'react-redux' ; import { useHistory } from 'react-router-dom' ; import { parsePath } from 'history' ; import { Identifier , Record } from '../types' ; import resolveRedirectTo from '../util/resolveRedirectTo' ; import { refreshView } from '../actions/uiActions' ; type RedirectToFunction = ( basePath ? : string , id ? : Identifier , data ? : Record , state ? : object ) => string ; export type RedirectionSideEffect = string | boolean | RedirectToFunction ; example const useRedirect = ( ) => { const dispatch = useDispatch ( ) ; const history = useHistory ( ) ; return useCallback ( ( redirectTo , basePath = '' , id ? , data ? , state = { } ) => { if ( ! redirectTo ) { if ( history . location . state || history . location . search ) { history . replace ( { ... history . location , state , search : undefined , } ) ; } dispatch ( refreshView ( ) ) ; return ; } if ( typeof redirectTo === 'string' && redirectTo . startsWith ( 'http' ) && window ) { window . location . href = redirectTo ; } else { history . push ( { ... parsePath ( resolveRedirectTo ( redirectTo , basePath , id , data ) ) , state : { _scrollToTop : true , ... state } , } ) ; } } , [ dispatch , history ] ) ; } ; export default useRedirect ;