2022-08-19 19:59:13 +02:00
|
|
|
import { useState, useEffect } from 'react';
|
2022-09-08 16:27:34 +02:00
|
|
|
import { emitCustomEvent } from 'react-custom-events';
|
2022-08-19 19:59:13 +02:00
|
|
|
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);
|
2022-09-08 16:27:34 +02:00
|
|
|
_setCart(data);
|
2022-08-19 19:59:13 +02:00
|
|
|
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);
|
2022-09-08 16:27:34 +02:00
|
|
|
_setCart(data);
|
2022-08-20 20:49:51 +02:00
|
|
|
setLoading(false);
|
|
|
|
};
|
|
|
|
|
2022-08-25 16:23:00 +02:00
|
|
|
useEffect(() => {
|
2022-09-07 16:57:07 +02:00
|
|
|
if (user && cart && (!cart.statistic_profile_id || !cart.operator_profile_id)) {
|
2022-08-25 16:23:00 +02:00
|
|
|
reloadCart();
|
|
|
|
}
|
|
|
|
}, [user]);
|
|
|
|
|
2022-09-08 16:27:34 +02:00
|
|
|
const _setCart = (data: Order) => {
|
|
|
|
setCart(data);
|
|
|
|
emitCustomEvent('CartUpdate', data);
|
|
|
|
};
|
|
|
|
|
|
|
|
return { loading, cart, error, setCart: _setCart, reloadCart };
|
2022-08-19 19:59:13 +02:00
|
|
|
}
|