Files
mwitnessing/components/ExampleForm.js
Dobromir Popov acd776e988 renames
2024-03-26 01:08:57 +02:00

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 ? "Редактирай" : "Създай"} 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 ? "Обнови" : "Създаи"}
</button>
</div>
</div>
);
}
}