51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
import { useMutation } from '@tanstack/react-query';
|
|
import { apiClient, ApiResponse, extractApiErrors } from '../../../lib/api-client';
|
|
import { useAuthStore } from '../store';
|
|
// import { toast } from 'react-hot-toast';
|
|
|
|
interface LoginCredentials {
|
|
username: string;
|
|
password: string;
|
|
}
|
|
|
|
interface LoginResponse {
|
|
name: string;
|
|
role: string;
|
|
token: string;
|
|
}
|
|
|
|
interface Callback {
|
|
onError?: (errors: Record<string, string>) => void;
|
|
}
|
|
|
|
export const login = async (credentials: LoginCredentials): Promise<LoginResponse> => {
|
|
const response = await apiClient.post<ApiResponse<LoginResponse>>('/api/v1/users/login', credentials);
|
|
|
|
console.log(response.data);
|
|
|
|
if (!response.data.data) {
|
|
throw new Error('Authentication failed');
|
|
}
|
|
return response.data.data;
|
|
};
|
|
|
|
export const useLogin = ({ onError }: Callback) => {
|
|
const { setUser, setToken } = useAuthStore();
|
|
|
|
return useMutation({
|
|
mutationFn: login,
|
|
onSuccess: (data) => {
|
|
setUser({
|
|
name: data.name,
|
|
role: data.role,
|
|
});
|
|
setToken(data.token);
|
|
// toast.success('Login berhasil');
|
|
},
|
|
onError: (error: unknown) => {
|
|
const errors = extractApiErrors(error);
|
|
|
|
onError && onError(errors);
|
|
},
|
|
});
|
|
}; |