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);
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
2022-08-20 20:49:51 +02:00
|
|
|
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]);
|
|
|
|
|
2022-08-20 20:49:51 +02:00
|
|
|
return { loading, cart, error, setCart, reloadCart };
|
2022-08-19 19:59:13 +02:00
|
|
|
}
|