121 lines
3.0 KiB
JavaScript
121 lines
3.0 KiB
JavaScript
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 (
|
|
<div className="w-full max-w-xs">
|
|
<h3>{router.query?.id ? "Edit" : "Create"} Item </h3>
|
|
<div className="mb-4">
|
|
<div className="form-check">
|
|
<input className="checkbox" type="checkbox" id="isactive" name="isactive" onChange={handleChange} checked={item.isactive} autoComplete="off" />
|
|
<label className="label" htmlFor="isactive">
|
|
Is Active</label>
|
|
</div>
|
|
</div>
|
|
<div className="panel-actions">
|
|
<Link href={urls.indexUrl} className="action-button"> обратно </Link>
|
|
<button className="button bg-blue-500 hover:bg-blue-700 focus:outline-none focus:shadow-outline" type="submit">
|
|
{router.query?.id ? "Update" : "Create"}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
);
|
|
}
|
|
}
|
|
|
|
|