import axios from "axios"; import React, { useCallback, useEffect, useState } from "react"; // import { API } from "../../data"; import { isAutheticated } from "../../auth"; import ClipLoader from "react-spinners/ClipLoader"; import swal from 'sweetalert'; // import "bootstrap"; // import "bootstrap/dist/css/bootstrap.css"; // import "bootstrap/dist/js/bootstrap.js"; import { Link, useParams } from "react-router-dom"; import { useHistory } from "react-router-dom"; function EditProducts() { const { token } = isAutheticated(); let history = useHistory(); const [state, setstate] = useState({ title: "", description: "", status: "", tax: "", price: "", taxes: [], loading: false, }); const { id } = useParams(); // console.log(id) const { title, description, status, tax, price, taxes, loading } = state; const changeState = (newState) => setstate((prevState) => ({ ...prevState, ...newState })); const fetchTax = useCallback(async () => { let res = await axios.get(`/api/tax/view_tax`, { headers: { Authorization: `Bearer ${token}`, }, }); if (res.status === 200) changeState({ taxes: res.data }); }, [token]); const fetchProduct = useCallback(async () => { const res = await axios.get(`/api/product/${id}`, { headers: { Authorization: `Bearer ${token}`, }, }); console.log(res.data); if (res.status === 200) changeState({ ...res.data }); }, [id, token]); useEffect(() => { fetchTax(); fetchProduct(); }, [fetchTax, fetchProduct]); useEffect(() => { if (!(typeof tax === "object")) return; changeState({ tax: tax.name }); }, [tax]); const handleSubmit = async () => { if (!(title || description || tax || price)) { alert("Please fill required field "); return; } changeState({ loading: true }); let res = await axios.put( `/api/product/${id}`, { title, description, status, tax: taxes.find((taxObj) => taxObj.name === tax)?._id, price, }, { headers: { Authorization: `Bearer ${token}`, }, } ); if (res.status === 200) window.location.reload(); changeState({ loading: false }); swal("Edit successfully!"); history.goBack() }; const onCancel = () => { // window.location = "/comproducts"; history.goBack() }; const handleChange = (e) => { const { name, value } = e.target; changeState({ [name]: value }); }; return (