cart
This commit is contained in:
106
hooks/useAuth.ts
106
hooks/useAuth.ts
@@ -0,0 +1,106 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Alert } from 'react-native';
|
||||
import * as authService from '../services/auth';
|
||||
|
||||
interface User {
|
||||
userId: number;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export const useAuth = () => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
|
||||
// Kiểm tra trạng thái đăng nhập khi khởi động
|
||||
useEffect(() => {
|
||||
checkAuthStatus();
|
||||
}, []);
|
||||
|
||||
const checkAuthStatus = async () => {
|
||||
try {
|
||||
const authenticated = await authService.isAuthenticated();
|
||||
setIsAuthenticated(authenticated);
|
||||
|
||||
if (authenticated) {
|
||||
const userData = await authService.getUser();
|
||||
setUser(userData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Check auth status error:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
try {
|
||||
const response = await authService.login(email, password);
|
||||
|
||||
setUser({
|
||||
userId: response.userId,
|
||||
email: response.email,
|
||||
});
|
||||
setIsAuthenticated(true);
|
||||
|
||||
Alert.alert('Thành công', 'Đăng nhập thành công!');
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error('Login error:', error);
|
||||
Alert.alert('Lỗi', error.message || 'Đăng nhập thất bại');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const register = async (email: string, password: string) => {
|
||||
try {
|
||||
const response = await authService.register(email, password);
|
||||
|
||||
// Sau khi đăng ký thành công, tự động đăng nhập
|
||||
if (response.token) {
|
||||
await authService.saveAuthData(response);
|
||||
setUser({
|
||||
userId: response.userId,
|
||||
email: response.email,
|
||||
});
|
||||
setIsAuthenticated(true);
|
||||
}
|
||||
|
||||
Alert.alert('Thành công', 'Đăng ký thành công!');
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error('Register error:', error);
|
||||
Alert.alert('Lỗi', error.message || 'Đăng ký thất bại');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
const token = await authService.getAuthToken();
|
||||
if (token) {
|
||||
await authService.logout(token);
|
||||
}
|
||||
|
||||
setUser(null);
|
||||
setIsAuthenticated(false);
|
||||
|
||||
Alert.alert('Thành công', 'Đăng xuất thành công!');
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error('Logout error:', error);
|
||||
Alert.alert('Lỗi', 'Đăng xuất thất bại');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
user,
|
||||
loading,
|
||||
isAuthenticated,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
checkAuthStatus,
|
||||
};
|
||||
};
|
||||
162
hooks/useCart.ts
162
hooks/useCart.ts
@@ -0,0 +1,162 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Alert } from 'react-native';
|
||||
import * as authService from '../services/auth';
|
||||
import cartService, { AddToCartRequest, CartResponse } from '../services/cart';
|
||||
|
||||
export const useCart = () => {
|
||||
const [cart, setCart] = useState<CartResponse | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
|
||||
// Lấy userId từ auth service
|
||||
const getUserId = async (): Promise<number | null> => {
|
||||
try {
|
||||
const isAuthenticated = await authService.isAuthenticated();
|
||||
if (!isAuthenticated) {
|
||||
console.log('User is not authenticated');
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await authService.getUser();
|
||||
console.log('getUserId - User data:', user);
|
||||
|
||||
if (user && typeof user.userId === 'number') {
|
||||
return user.userId;
|
||||
}
|
||||
|
||||
if (user) {
|
||||
console.warn('User exists but userId is missing or invalid:', user);
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Error getting userId:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Tải giỏ hàng
|
||||
const loadCart = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const userId = await getUserId();
|
||||
if (!userId) {
|
||||
setCart(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await cartService.getCart(userId);
|
||||
setCart(data);
|
||||
} catch (error: any) {
|
||||
console.error('Load cart error:', error);
|
||||
const errorMessage = error?.message || '';
|
||||
|
||||
if (errorMessage.includes('404') || errorMessage.includes('Not Found') || errorMessage.includes('not found')) {
|
||||
setCart(null);
|
||||
} else if (!errorMessage.includes('User not logged in')) {
|
||||
console.warn('Failed to load cart:', errorMessage);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Refresh giỏ hàng
|
||||
const refreshCart = useCallback(async () => {
|
||||
try {
|
||||
setRefreshing(true);
|
||||
await loadCart();
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, [loadCart]);
|
||||
|
||||
// Thêm sản phẩm vào giỏ hàng
|
||||
const addToCart = useCallback(async (productId: number, quantity: number = 1) => {
|
||||
try {
|
||||
console.log('=== useCart: addToCart START ===', { productId, quantity });
|
||||
const userId = await getUserId();
|
||||
if (!userId) {
|
||||
Alert.alert('Thông báo', 'Vui lòng đăng nhập để thêm vào giỏ hàng');
|
||||
return false;
|
||||
}
|
||||
|
||||
const updatedCart = await cartService.addToCart(userId, { productId, quantity });
|
||||
console.log('=== useCart: addToCart SUCCESS - Setting cart ===', updatedCart);
|
||||
setCart(updatedCart); // Cập nhật state ngay lập tức
|
||||
Alert.alert('Thành công', 'Đã thêm sản phẩm vào giỏ hàng');
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
console.error('=== useCart: addToCart ERROR ===', error);
|
||||
Alert.alert('Lỗi', 'Không thể thêm sản phẩm vào giỏ hàng');
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Cập nhật số lượng sản phẩm
|
||||
const updateQuantity = useCallback(async (cartItemId: number, quantity: number) => {
|
||||
try {
|
||||
const userId = await getUserId();
|
||||
if (!userId) return false;
|
||||
|
||||
const updatedCart = await cartService.updateCartItem(userId, cartItemId, { quantity });
|
||||
setCart(updatedCart); // Cập nhật state ngay lập tức
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Update quantity error:', error);
|
||||
Alert.alert('Lỗi', 'Không thể cập nhật số lượng');
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Xóa một sản phẩm
|
||||
const removeItem = useCallback(async (cartItemId: number) => {
|
||||
try {
|
||||
const userId = await getUserId();
|
||||
if (!userId) return false;
|
||||
|
||||
const updatedCart = await cartService.removeCartItem(userId, cartItemId);
|
||||
setCart(updatedCart); // Cập nhật state ngay lập tức
|
||||
Alert.alert('Thành công', 'Đã xóa sản phẩm khỏi giỏ hàng');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Remove item error:', error);
|
||||
Alert.alert('Lỗi', 'Không thể xóa sản phẩm');
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Xóa tất cả sản phẩm
|
||||
const clearCart = useCallback(async () => {
|
||||
try {
|
||||
const userId = await getUserId();
|
||||
if (!userId) return false;
|
||||
|
||||
await cartService.clearCart(userId);
|
||||
setCart(null);
|
||||
Alert.alert('Thành công', 'Đã xóa tất cả sản phẩm');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Clear cart error:', error);
|
||||
Alert.alert('Lỗi', 'Không thể xóa giỏ hàng');
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Load cart khi component mount
|
||||
useEffect(() => {
|
||||
loadCart();
|
||||
}, [loadCart]);
|
||||
|
||||
return {
|
||||
cart,
|
||||
loading,
|
||||
refreshing,
|
||||
loadCart,
|
||||
refreshCart,
|
||||
addToCart,
|
||||
updateQuantity,
|
||||
removeItem,
|
||||
clearCart,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user