Event start and end time not correctly set when using formData.append() in React POST request

116 Views Asked by At

I am currently developing a React project where I need to create and save an event to a database. The frontend of the project is built using React, and I'm sending the event details as a JSON object along with an event flyer file to the backend. To ensure proper transmission of these details, I am using the formData.append() function in my POST request.

However, I'm facing an issue where the event start and end date and time are not being properly saved. Before the formData.append() function, the event start and end time are set correctly, but after the formData.append() function, the time is set to the current time and only the date remains as provided.

So here is the code that I'm using :

export default function AddEvent() {
  let navigate = useNavigate();
  const [event, setEvent] = useState({
    eventName: "",
    eventType: "",
    eventLocationType: "",
  });
  const [location, setLocation] = useState("");
  const [startTime, setStartTime] = useState(moment());
  const [endTime, setEndTime] = useState(moment());
  const [selectedImage, setSelectedImage] = useState(undefined);
  const [imageUrl, setImageUrl] = useState(null);

  const { eventName, eventType, eventLocationType } = event;
const onInputChange = (e) => {
    if (e && e.target && e.target.name) {
      setEvent({ ...event, [e.target.name]: e.target.value });
    }
  };

  const handleLocationChange = (event, value) => {
    setLocation(event.target.value);
  };

  const handleStartTimeChange = (event) => {
    if (event && event.target && event.target.name) {
    setStartTime(moment(event.target.value));
      //setStartTime(event.target.value);
    }
  };

  const handleEndTimeChange = (event) => {
    if (event && event.target && event.target.name) {
    setEndTime(moment(event.target.value));
      //setEndTime(event.target.value);
    }
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    console.log({ ...event, location, startTime, endTime, selectedImage });
    const formData = new FormData();
    formData.append("file", selectedImage);
    formData.append(
      "body",
      JSON.stringify({
        ...event,
        location,
        startTime,
        endTime,
      })
    );
    for (let pair of formData.entries()) {
      console.log(pair[0] + ": " + pair[1]);
    }
    
    await axios
      .post("http://localhost:8080/api/event/saveEvent", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      .then((response) => {
        console.log(response);
        Swal.fire({
          title: "Event saved successfully!",
          icon: "success",
          confirmButtonText: "OK",
        }).then(() => {
          navigate("/");
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

 return (
    <div style={{ paddingBottom: "30px" }}>
 <FormControl
        encType="multipart/form-data"
        onSubmit={(e) => onSubmit(e)}
        sx={{ display: "flex", width: "50%", paddingLeft: "250px" }}
      >
<FormLabel
              disabled={true}
              sx={{
                paddingBottom: "10px",
                display: "flex",
                justifyContent: "flex-start",
              }}
            >
              Event Start Date & Time
            </FormLabel>
            <LocalizationProvider dateAdapter={AdapterDayjs}>
              <DemoContainer components={["DateTimeField"]}>
                <DateTimeField
                  size="small"
                  label="Start Date & Time"
                  name="startTime"
                  value={startTime}
                  onChange={handleStartTimeChange}
                  sx={{
                    "& .Mui-focus": {
                      "&:focus": {
                        outline: "none",
                        color: "grey",
                      },
                    }
                  }}
                />
              </DemoContainer>
            </LocalizationProvider>
          </div>

          <div>
            <FormLabel
              disabled={true}
              sx={{
                paddingBottom: "10px",
                display: "flex",
                justifyContent: "flex-start",
              }}
            >
              Event End Date & Time
            </FormLabel>
            <LocalizationProvider dateAdapter={AdapterDayjs}>
              <DemoContainer components={["DateTimeField"]}>
                <DateTimeField
                  size="small"
                  label="End Date & Time"
                  name="endTime"
                  value={endTime}
                  onChange={handleEndTimeChange}
                />
              </DemoContainer>
            </LocalizationProvider>
          </div>
        </div>
<Box
          sx={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "flex-end",
          }}
        >
          <Button
            variant="outlined"
            onClick={onCancel}
            style={{ color: "#e6b81a", borderColor: "#e6b81a" }}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            onClick={onSubmit}
            style={{ backgroundColor: "#e6b81a", marginLeft: "10px" }}
          >
            Save
          </Button>
        </Box>
      </FormControl>
</div>
  );
}

I'm unable to find the error behind this. I'm looking for guidance on how to fix this problem. Any help or suggestions would be greatly appreciated.

1

There are 1 best solutions below

0
Vidushika Dasanayka On

The problem I previously posted about was resolved by myself. Further investigation and testing led me to the conclusion that the startTime and endTime values being sent in the formData were the root of the issue.

I submit the startTime and endTime values as moment objects to the onSubmit function. However, the moment objects are not correctly converted to string values when you serialize the JSON object using JSON.stringify().

Before adding the moment objects to the formData,  can convert them to string values to resolve this problem. The moment object's format() method can be used to turn it into a string with a certain format. I used the  following code to change the startTime and endtime values to the format YYYY-MM-DDTHH:mm:ss:

formData.append(
  "body",
  JSON.stringify({
    ...event,
    location,
    startTime: startTime.format("YYYY-MM-DDTHH:mm:ss"),
    endTime: endTime.format("YYYY-MM-DDTHH:mm:ss"),
  })
);