import axiosInstance from '../src/axiosSecure'; import { useEffect, useState } from "react"; import toast from "react-hot-toast"; import { useRouter } from "next/router"; import Link from "next/link"; class ExampleForm extends React.Component { constructor(props) { super(props); this.state = { urls: { apiUrl: "/api/data/...", indexUrl: "/cart/..." }, isEdit: false, }; } componentDidMount() { if (this.props.id) { this.fetch(this.props.id); } } fetch = async (id) => { try { const { data } = await axiosInstance.get(this.state.urls.apiUrl + id); this.setState({ item: data }); } catch (error) { console.error(error); } }; render() { const urls = { apiUrl: "/api/data/...s", indexUrl: "/cart/...s" } const [item, set] = useState({ isactive: true, }); const router = useRouter(); useEffect(() => { const fetch = async (id) => { try { const { data } = await axiosInstance.get(urls.apiUrl + id); set(data); } catch (error) { console.error(error); } }; if (router.query?.id) { fetch(parseInt(router.query.id.toString())); } console.log("called"); }, [router.query.id]); handleChange = ({ target }) => { if (target.name === "isactive") { set({ ...item, [target.name]: target.checked }); } else if (target.name === "age") { set({ ...item, [target.name]: parseInt(target.value) }); } else { set({ ...item, [target.name]: target.value }); } } handleSubmit = async (e) => { e.preventDefault(); try { if (router.query?.id) { await axiosInstance.put(urls.apiUrl + router.query.id, { ...item, }); toast.success("Task Updated", { position: "bottom-center", }); } else { await axiosInstance.post(urls.apiUrl, item); toast.success("Task Saved", { position: "bottom-center", }); } router.push(indexUrl); } catch (error) { toast.error(error.response.data.message); } }; return (

{router.query?.id ? "Edit" : "Create"} Item

обратно
); } }