edit events

This commit is contained in:
Harini312821
2024-08-12 01:21:35 +08:00
parent fbedd28d3b
commit 3162cc0675
5 changed files with 219 additions and 110 deletions

View File

@@ -1,5 +1,5 @@
import { useState, useEffect } from "react";
import { Button } from "@nextui-org/react";
import { Button, Input, Image } from "@nextui-org/react";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import axios from "axios";
@@ -7,8 +7,10 @@ import { useNavigate, useParams } from "react-router-dom";
import NextUIFormikInput from "../components/NextUIFormikInput";
import NextUIFormikTextarea from "../components/NextUIFormikTextarea";
import config from "../config";
import InsertImage from "../components/InsertImage";
import { ArrowUTurnLeftIcon } from "../icons";
import EventsPicture from "../components/EventsPicture";
import NextUIFormikSelect from "../components/NextUIFormikSelect";
import instance from "../security/http"
// Validation schema
const validationSchema = Yup.object({
@@ -42,39 +44,33 @@ const validationSchema = Yup.object({
const EditEventsPage = () => {
const [eventData, setEventData] = useState<any>(null);
const [imageFile, setImageFile] = useState<File | null>(null); // State to handle image file
const [townCouncils, setTownCouncils] = useState<string[]>([]);
const { id } = useParams(); // Get event ID from URL
const navigate = useNavigate();
const fetchEvent = async () => {
try {
const res = await axios.get(`${config.serverAddress}/events/${id}`);
console.log("Fetched event data:", res.data); // Log the fetched data
setEventData(res.data);
} catch (error) {
console.error("Failed to fetch event:", error);
}
};
const fetchTownCouncils = async () => {
try {
const res = await axios.get(`${config.serverAddress}/users/town-councils-metadata`);
setTownCouncils(JSON.parse(res.data).townCouncils);
} catch (error) {
console.error("Failed to fetch town councils:", error);
}
};
useEffect(() => {
const fetchEvent = async () => {
try {
const res = await axios.get(`${config.serverAddress}/events/${id}`);
console.log("Fetched event data:", res.data); // Log the fetched data
setEventData(res.data);
if (res.data.evtPicture) {
// Optionally handle existing image
setImageFile(null); // You might want to set this to the existing image URL if applicable
}
} catch (error) {
console.error("Failed to fetch event:", error);
}
};
const fetchTownCouncils = async () => {
try {
const res = await axios.get(`${config.serverAddress}/users/town-councils-metadata`);
setTownCouncils(JSON.parse(res.data).townCouncils);
} catch (error) {
console.error("Failed to fetch town councils:", error);
}
};
fetchEvent();
fetchTownCouncils();
}, [id]);
}, []);
const initialValues = {
title: eventData?.title || "",
@@ -84,44 +80,22 @@ const EditEventsPage = () => {
location: eventData?.location || "",
category: eventData?.category || "",
slotsAvailable: eventData?.slotsAvailable || "",
evtPicture: null, // Initialize with null or handle separately
};
const handleSubmit = async (
values: any,
{ setSubmitting, resetForm, setFieldError }: any
) => {
console.log("From data:", values)
const formData = new FormData();
formData.append("title", values.title);
formData.append("description", values.description);
formData.append("date", values.date);
formData.append("time", values.time);
formData.append("location", values.location);
formData.append("category", values.category);
formData.append("slotsAvailable", values.slotsAvailable);
if (imageFile) {
formData.append("evtPicture", imageFile); // Append image file to form data
}
try {
const response = await axios.put(
const response = await instance.put(
`${config.serverAddress}/events/${id}`,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
values,
);
console.log("Server response:", response); // Debug log
if (response.status === 200 || response.status === 201) {
console.log("Event updated successfully:", response.data);
resetForm(); // Clear form after successful submit
setImageFile(null); // Reset image file state
navigate("/admin/events");
window.location.href = "/admin/events";
} else {
console.error("Error updating event:", response.statusText);
}
@@ -142,7 +116,7 @@ const EditEventsPage = () => {
<Button
variant="light"
onPress={() => {
navigate(-1);
window.location.href = "/admin/events";
}}
>
<ArrowUTurnLeftIcon />
@@ -155,7 +129,7 @@ const EditEventsPage = () => {
onSubmit={handleSubmit}
enableReinitialize={true} // Ensure form updates with new data
>
{({ isValid, dirty, isSubmitting, setFieldValue }) => (
{({ isValid, dirty, isSubmitting }) => (
<Form className="flex flex-col gap-5">
<NextUIFormikInput
label="Title"
@@ -184,20 +158,18 @@ const EditEventsPage = () => {
labelPlacement="inside"
/>
<div>
<label className="block text-gray-700">Location</label>
<select
name="location"
className="form-select mt-1 block w-full"
onChange={(e) => setFieldValue("location", e.target.value)}
value={eventData?.location || ""}
>
<option value="">Select a town council</option>
{townCouncils.map((townCouncil, index) => (
<option key={index} value={townCouncil}>
{townCouncil}
</option>
))}
</select>
{townCouncils.length > 0 && (
<NextUIFormikSelect
label="Town council"
name="location"
placeholder="Choose the town council for the event"
labelPlacement="inside"
options={townCouncils.map((townCouncil) => ({
key: townCouncil,
label: townCouncil,
}))}
/>
)}
</div>
<NextUIFormikInput
label="Category"
@@ -213,22 +185,16 @@ const EditEventsPage = () => {
placeholder="Enter slots available"
labelPlacement="inside"
/>
<div className="mb-4">
<InsertImage
onImageSelected={(file) => {
setImageFile(file); // Set image file
setFieldValue("evtPicture", file); // Set form field value
}}
// Optionally handle displaying current image
/>
<div className="mb-4 flex flex-col ">
<EventsPicture eventId={id as string} editable/>
</div>
<div className="flex flex-row-reverse border">
<Button
type="submit"
className="bg-red-600 text-white text-xl w-1/6"
className="bg-red-600 text-white text-xl"
disabled={!isValid || !dirty || isSubmitting}
>
<p>Edit Event</p>
<p>Save</p>
</Button>
</div>
</Form>