Home > Enterprise >  React event.preventDefault() is not working when uploading attachment
React event.preventDefault() is not working when uploading attachment

Time:06-30

I have an attachment upload feature using React-Bootstrap form and unfortunately, every time I upload an attachment, the page keeps refreshing and signs me out of the application. I have inserted e.preventDefault() in all functions; saveFile which saves the name of the file from input, backToProject which returns to the previous page, and uploadFile to upload the file to MySQL using NodeJS. However, it does not work.

import React, { useState, useContext } from "react";
import { Form, Button, Card } from "react-bootstrap";
import Axios from "axios";
import { useHistory } from "react-router-dom";
import { UserContext, UserTypeContext } from "./../Helper/Context";

function AddAttachment() {
  const history = useHistory();

  const { userId, setUserId } = useContext(UserContext);
  const { type, isUserType } = useContext(UserTypeContext);

  const link = window.location.pathname;
  const split = link.split("/");
  const projectId = split[4];

  const [proCode, setProCode] = useState("");

  const [file, setFile] = useState();
  const [fileName, setFileName] = useState("");

  const saveFile = (event) => {
    event.preventDefault();
    setFile(event.target.files[0]);
    setFileName(event.target.files[0].name);
  };

  const uploadFile = async (e, projectId) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append("file", file);
    formData.append("fileName", fileName);
    formData.append("projectId", projectId);
    try {
      const res = await Axios.post(
        "http://localhost:3001/uplatt",
        formData
      ).then((res) => {
        if (res.data.successfulAdd) {
          if (type === "Staff") {
            window.alert("You have successfully uploaded an attachment!");
            history.push(`/staff/${userId}/viewproject/${projectId}`);
          } else if (type === "Student") {
            window.alert("You have successfully uploaded an attachment!");
            history.push(`/student/${userId}/viewproject/${projectId}`);
          }
        }
      });
    } catch (ex) {
      console.log(ex);
    }
  };

  const backToProject = (e) => {
    e.preventDefault();

    if (type === "Staff") {
      history.push(`/staff/${userId}/viewproject/${projectId}`);
    } else if (type === "Student") {
      history.push(`/student/${userId}/viewproject/${projectId}`);
    }
  };

  return (
    <div className="d-flex justify-content-center">
      <Card style={{ width: "70%" }}>
        <div className="mt-3 p-5">
          <h3>Add new attachment</h3>
          <hr />
          <Form onSubmit={(e) => uploadFile(e, projectId)}>
            <div className="mt-1 mb-3">
              <input type="file" name="file" onChange={saveFile} />
            </div>
            <div className="d-flex flex-end justify-content-end align-items-end mt-3">
              <div className="px-3">
                <Button
                  type="button"
                  style={{ color: "white", backgroundColor: "#104271" }}
                  onClick={backToProject}
                  className="mr-3"
                >
                  Cancel
                </Button>
              </div>
              <div>
                <Button
                  type="submit"
                  style={{ color: "white", backgroundColor: "#104271" }}
                >
                  Upload
                </Button>
              </div>
            </div>
          </Form>
        </div>
      </Card>
    </div>
  );
}

export default AddAttachment;

I am just wondering what is wrong with my code? Can anybody please, please help me with this? Thank you!

CodePudding user response:

Your page refresh before the upload end.

You can remove type="submit" from the button and call uploadFile function in in button directly.

<Button style={{ color: "white", backgroundColor: "#104271" }}
onClick={async () => {
// do somthing else before
await uploadFile(projectId);
// do somthing else after
}}> Upload </Button>

CodePudding user response:

I found a solution but absolutely have no idea why. I changed from client side to server side (uploaded the files to public/images of server instead of client) and boom, the problem's gone.

  • Related