ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
79 lines • 2.76 kB
JavaScript
import { useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useNotificationContext } from "../notification/index.js";
import { useBasename, useLocation, useNavigate } from "../routing/index.js";
import useAuthProvider, { defaultAuthParams } from "./useAuthProvider.js";
import { removeDoubleSlashes } from "../routing/useCreatePath.js";
/**
* Get a callback for calling the authProvider.login() method
* and redirect to the previous authenticated page (or the home page) on success.
*
* @see useAuthProvider
*
* @returns {Function} login callback
*
* @example
*
* import { useLogin } from 'react-admin';
*
* const LoginButton = () => {
* const [loading, setLoading] = useState(false);
* const login = useLogin();
* const handleClick = {
* setLoading(true);
* login({ username: 'john', password: 'p@ssw0rd' }, '/posts')
* .then(() => setLoading(false));
* }
* return <button onClick={handleClick}>Login</button>;
* }
*/
const useLogin = () => {
const authProvider = useAuthProvider();
const queryClient = useQueryClient();
const location = useLocation();
const locationState = location.state;
const navigate = useNavigate();
const basename = useBasename();
const { resetNotifications } = useNotificationContext();
const nextPathName = locationState && locationState.nextPathname;
const nextSearch = locationState && locationState.nextSearch;
const afterLoginUrl = removeDoubleSlashes(`${basename}/${defaultAuthParams.afterLoginUrl}`);
const login = useCallback((params = {}, pathName) => {
if (authProvider) {
return authProvider.login(params).then(ret => {
resetNotifications();
queryClient.invalidateQueries({
queryKey: ['auth', 'getPermissions'],
});
if (ret && ret.hasOwnProperty('redirectTo')) {
if (ret) {
navigate(ret.redirectTo);
}
}
else {
const redirectUrl = pathName
? pathName
: nextPathName + nextSearch || afterLoginUrl;
navigate(redirectUrl);
}
return ret;
});
}
else {
resetNotifications();
navigate(afterLoginUrl);
return Promise.resolve();
}
}, [
authProvider,
queryClient,
navigate,
nextPathName,
nextSearch,
resetNotifications,
afterLoginUrl,
]);
return login;
};
export default useLogin;
//# sourceMappingURL=useLogin.js.map