import React, { useState, useEffect } from "react";
import {
COLLECTION_ID_USERS,
DATABASE_ID,
databases,
} from "../../appwriteConfig";
import { ID } from "appwrite";
import {
FaRegPaperPlane,
FaArrowLeftLong,
FaArrowRightLong,
} from "react-icons/fa6";
import { FileUpload, ParentInfo, StudentInfo } from "..";
import * as yup from "yup";
import "./multistepForm.css";
const MultistepForm = () => {
const [step, setStep] = useState(0);
const [formData, setFormData] = useState({
stdName: "",
stdMiddleName: "",
stdSurname: "",
stdGender: "",
stdPOB: "",
stdDOB: "",
fatherName: "",
motherName: "",
});
const handleNavigation = (action) => {
if (action === "next" && step < FormHeaders.length - 1) {
setStep(step + 1);
} else if (action === "back" && step > 0) {
setStep(step - 1);
} else if (action === "submit") {
alert("Submission completed");
}
};
const handleSubmit = async (e) => {
e.preventDefault();
let response = await databases.createDocument(
DATABASE_ID,
COLLECTION_ID_USERS,
ID.unique(),
formData
);
console.log("Created", response);
if (step !== FormHeaders.length - 1) {
handleNavigation("next");
} else {
handleNavigation("submit");
}
};
const FormHeaders = [
"Student Information",
"Parent Information",
"Upload Files",
];
const StepDisplay = () => {
switch (step) {
case 0:
return <StudentInfo formData={formData} setFormData={setFormData} />;
case 1:
return <ParentInfo formData={formData} setFormData={setFormData} />;
default:
return <FileUpload formData={formData} setFormData={setFormData} />;
}
};
return (
<div className="form">
<h2 className="form-title">Online Application</h2>
<div className="progressbar">
<div
style={{
width: step === 0 ? "33.3%" : step === 1 ? "66.6%" : "100%",
}}
></div>
</div>
<div className="form-container">
<h1 className="form-header">{FormHeaders[step]}</h1>
<div className="form-body">
<form onSubmit={handleSubmit} action="#">
{StepDisplay()}
<div className="form-footer">
{step !== 0 && (
<button
type="button"
className="form-btn btn"
onClick={() => handleNavigation("back")}
>
<FaArrowLeftLong />
</button>
)}
<button className="form-btn btn next" type="submit">
{step === FormHeaders.length - 1 ? (
<h2 className="next-page">
Submit
<i>
<FaRegPaperPlane />
</i>
</h2>
) : (
<h2 className="next-page">
Next Page
<i>
<FaArrowRightLong />
</i>
</h2>
)}
</button>
</div>
</form>
</div>
</div>
</div>
);
};
export default MultistepForm;
I am trying to submit my multistep form in reactJS, but every time I do so, I notice in the console that the form is being submitted three times, which means that every time I click on the “Next” button, the form is being submitted. That means that the “Next” button is still having the action of submitting.
I would really need help troubleshooting the handleSubmit function so that the form gets submitted when the “Submit” button is clicked. Thanks in advance.
Also, I wanted to know how I can clear the form data and go back right at the beginning once the form is submitted.