Upon making the necessary changes to the body type, I encountered a 400 error.
import Cookies from "js-cookie";
export default async function submitFormDataWithVehicleDetails(formData: FormData) {
const url = "http://127.0.0.1:3000/api/v1/hire";
const token = Cookies.get("token");
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
body: formData,
});
if (!response.ok) {
const errorResponse = await response.json();
throw new Error(
`Failed request with status ${response.status}, ${JSON.stringify(
errorResponse
)}`
);
}
const data = await response.json();
return data;
}
"use client";
import { useState } from "react";
import submitFormDataWithVehicleDetails from "@/lib/postHire";
export default function Form({ vehicle }: { vehicle: Vehicle }) {
const {
name,
seat,
price,
description,
type,
pictures,
colour,
transmission,
} = vehicle;
const [note, setNote] = useState("");
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const vehicleDetails: FormDetails = {
name: name,
pictures: pictures,
description: description,
colour: colour,
transmission: transmission,
type: type,
seat: seat,
price: price,
};
const formData = new FormData();
formData.append("note", note);
Object.entries(vehicleDetails).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item, index) => {
formData.append(`${key}[${index}]`, item);
});
} else {
formData.append(key, typeof value === "number" ? String(value) : value);
}
});
try {
await submitFormDataWithVehicleDetails(formData);
console.log("Submission Successful");
} catch (error) {
console.error(error);
}
}
return (
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="examplenote1" className="form-label">
Include Note
</label>
<input
type="text"
className="form-control"
id="exampleInputEmail1"
aria-describedby="textHelp"
placeholder="Don't forget snacks"
value={note}
onChange={(e) => {
setNote(e.target.value);
}}
/>
</div>
<button type="submit" className="btn btn-primary">
Submit
</button>
</form>
);
}
No other modifications have been made.