1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-23 12:52:20 +01:00

45 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-08-19 19:59:13 +02:00
import { useState, useEffect } from 'react';
import { Order } from '../models/order';
import CartAPI from '../api/cart';
import { getCartToken, setCartToken } from '../lib/cart-token';
2022-08-25 16:23:00 +02:00
import { User } from '../models/user';
2022-08-19 19:59:13 +02:00
2022-08-25 16:23:00 +02:00
export default function useCart (user?: User) {
2022-08-19 19:59:13 +02:00
const [cart, setCart] = useState<Order>(null);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState(null);
useEffect(() => {
async function createCart () {
const currentCartToken = getCartToken();
const data = await CartAPI.create(currentCartToken);
setCart(data);
setLoading(false);
setCartToken(data.token);
}
setLoading(true);
try {
createCart();
} catch (e) {
setLoading(false);
setError(e);
}
}, []);
const reloadCart = async () => {
setLoading(true);
const currentCartToken = getCartToken();
const data = await CartAPI.create(currentCartToken);
setCart(data);
setLoading(false);
};
2022-08-25 16:23:00 +02:00
useEffect(() => {
if (user && cart && (!cart.statistic_profile_id || !cart.operator_id)) {
reloadCart();
}
}, [user]);
return { loading, cart, error, setCart, reloadCart };
2022-08-19 19:59:13 +02:00
}