import { useCallback } from 'react' ; import { useDispatch } from 'react-redux' ; import useAuthProvider , { defaultAuthParams } from './useAuthProvider' ; import { clearState } from '../actions/clearActions' ; import { useHistory } from 'react-router-dom' ; import { LocationDescriptorObject } from 'history' ; see useAuthProvider returns { Function } example const useLogout = ( ) : Logout => { const authProvider = useAuthProvider ( ) ; const dispatch = useDispatch ( ) ; /**
     * We need the current location to pass in the router state
     * so that the login hook knows where to redirect to as next route after login.
     *
     * But if we used useLocation to get it, the logout function
     * would be rebuilt each time the user changes location. Consequently, that
     * would force a rerender of all components using this hook upon navigation
     * (CoreAdminRouter for example).
     *
     * To avoid that, we read the location directly from history which is mutable.
     * See: https://reacttraining.com/react-router/web/api/history/history-is-mutable
     */ const history = useHistory ( ) ; const logout = useCallback ( ( params = { } , redirectTo = defaultAuthParams . loginUrl , redirectToCurrentLocationAfterLogin = true ) => authProvider . logout ( params ) . then ( redirectToFromProvider => { dispatch ( clearState ( ) ) ; if ( redirectToFromProvider === false ) { return ; } const redirectToParts = ( redirectToFromProvider || redirectTo ) . split ( '?' ) ; const newLocation = { pathname : redirectToParts [ 0 ] , } ; if ( redirectToCurrentLocationAfterLogin && history . location && history . location . pathname ) { newLocation . state = { nextPathname : history . location . pathname , nextSearch : history . location . search , } ; } if ( redirectToParts [ 1 ] ) { newLocation . search = redirectToParts [ 1 ] ; } history . push ( newLocation ) ; return redirectToFromProvider ; } ) , [ authProvider , history , dispatch ] ) ; const logoutWithoutProvider = useCallback ( _ => { history . push ( { pathname : defaultAuthParams . loginUrl , state : { nextPathname : history . location && history . location . pathname , } , } ) ; dispatch ( clearState ( ) ) ; return Promise . resolve ( ) ; } , [ dispatch , history ] ) ; return authProvider ? logout : logoutWithoutProvider ; } ; param { Object } params param { string } redirectTo param { boolean } redirectToCurrentLocationAfterLogin return { Promise } type Logout = ( params ? : any , redirectTo ? : string , redirectToCurrentLocationAfterLogin ? : boolean ) => Promise < any > ; export default useLogout ;