import React, { useState } from 'react'; import { useAddStockAlertMutation } from '@akinon/next/data/client/wishlist'; import { Trans } from '@akinon/next/components/trans'; import { useLocalization } from '@akinon/next/hooks'; interface UseStockAlertProps { productPk: number; userEmail?: string; } export const useStockAlert = ({ productPk, userEmail }: UseStockAlertProps) => { const { t } = useLocalization(); const [isModalOpen, setIsModalOpen] = useState(false); const [stockAlertResponseMessage, setStockAlertResponseMessage] = useState(null); const [productError, setProductError] = useState(null); const [addStockAlert, { isLoading: isAddToStockAlertLoading }] = useAddStockAlertMutation(); const handleSuccess = () => { setStockAlertResponseMessage(React.createElement( Trans, { i18nKey: "product.stock_alert.success_description", components: { Email: React.createElement('span', {}, userEmail) } } )); setIsModalOpen(true); setProductError(null); }; const handleError = (err: any) => { if (err.status !== 401) { setStockAlertResponseMessage( t('product.stock_alert.error_description').toString() ); setIsModalOpen(true); } }; const addProductToStockAlertList = async () => { try { await addStockAlert({ productPk, email: userEmail }) .unwrap() .then(handleSuccess) .catch(handleError); } catch (error: any) { setProductError(error?.data?.non_field_errors || null); } }; const closeModal = () => { setIsModalOpen(false); }; const clearError = () => { setProductError(null); }; return { addProductToStockAlertList, isModalOpen, setIsModalOpen, stockAlertResponseMessage, productError, isAddToStockAlertLoading, closeModal, clearError }; };