Search code examples
reactjspostinputsubmitform-submit

Among two input fields one is taking just one letter and submit the form automatically. Why?


I was working on a MERN blog website project. In the Write post section there are two input fields. One is for Title & another is for description. When I try to write a post the title can be written fully but when I try to write the description the form getting submitted automatically after typing just one letter.

If I try to write the description first it also taking several word but this time the title is taking one letter and submitting the form automatically as sson as I try to type the second letter.

I'm attaching my code here! Can you please help me to solve this issue?

import { useContext, useState } from "react"
import "./write.css";
import {Context} from "../../context/Context";
import axios from "axios";

export default function Write() {
    const [title, setTitle] = useState("");
    const [desc, setDesc] = useState("");
    const [file, setFile] = useState(null);
    const { user } = useContext(Context);

    const handleSubmit = async (e) => {
        e.preventDefault();
        const newPost = {
            username: user.username,
            title,
            desc,
        };
        if (file) {
            const data = new FormData();
            const filename = Date.now() + file.name;
            data.append("name", filename);
            data.append("file", file);
            newPost.photo = filename;
            try {
                await axios.post("/upload", data);
            } catch (err) {}
        }
        try {
            const res = await axios.post("/posts", newPost);
            window.location.replace("/post/" + res.data._id);
        } catch (err) {
            
        }
    };
  return (
      <div className="write">
          {file && 
          <img src={URL.createObjectURL(file)} alt="" className="writeImg" />
          }
          <form className="writeForm" onChange={handleSubmit}>
              <div className="writeFormGroup">
                  <label htmlFor="fileInput">
                     <i class="writeIcon fa-solid fa-plus"></i>
                  </label>
                  <input type="file" id="fileInput" style={{display:"none"}} onChange={(e)=> setFile(e.target.files[0])} />
                  <input type="text" placeholder="Title" className="writeInput" autoFocus={true} onChange={e=> setTitle(e.target.value)} />
              </div>
              <div className="writeFormGroup">
                  <textarea placeholder="Tell your story..." type="text" className="writeInput writeText" onChange={e=> setDesc(e.target.value)}></textarea>
              </div>
              <button className="writeSubmit" type="submit">Publish</button>
          </form>
      </div>
  )
}

Solution

  • In your form, you should change this: <form className="writeForm" onChange={handleSubmit}> to this: <form className="writeForm" onSubmit={handleSubmit}>. Changing onChange to onSubmit should solve the issue