Form submit send nothing / req.file is undefined on the backend

Viewed 35

By clicking, a file selection window opens, the file is attached, the request leaves. The form is submitted through hooks, however, the backend (multer) does not receive the req.file. Help me to understand my mistake. I tried to use FileReader, but don't have any of required tags (I don`t know why they are required).

import React, { useRef } from "react";
import { logout } from "../../Redux/Auth/Auth-operations";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { getNickname } from "../../Redux/selectors";
import styles from "./LogOut.module.css";
import anonym from "../../img/anonymGit.png";

export default function LogOut({ id }) {
  const nickName = useSelector(getNickname);
  const inputAvatar = useRef();
  const formAvatar = useRef();

  const dispatch = useDispatch();
  const handleLogout = (e) => {
    e.preventDefault();
    dispatch(logout(id));
  };

  return (
    <div>
      <form
        id="avatars"
        ref={formAvatar}
        method="POST"
        action="http://localhost:3000/avatars"
        enctype="multipart/form-data"
      >
        <span>
          <input
            id="avatars"
            type="file"
            accept="image/jpeg, image/png"
            // method="POST"
            // action="/http://localhost:3000/avatars"
            ref={inputAvatar}
            className={styles.avatarInput}
            onChange={() => {
              // console.log("Инпут с файлом", inputAvatar.current.files[0]);
              // var fReader = new FileReader();
              // fReader.readAsDataURL(inputAvatar.current.files[0]);
              // fReader.onloadend = function (event) {
              //   var img = inputAvatar.current.files[0];
              //   console.log(img);
              //   img.src = event.target.result;
              //   console.log(img.src);
              // };
              console.log(formAvatar);
              console.log(formAvatar.current.value);
              console.log(inputAvatar.current.value);
              formAvatar.current.submit();
            }}
          />
          <button
            type="button"
            className={styles.avatarChoose}
            onClick={() => inputAvatar.current.click()}
          >
            <img src={anonym} className={styles.anonym} alt="" />
          </button>
          {nickName}
        </span>
      </form>
      <button onClick={handleLogout} className={styles.logOutBtn}>
        Logout
      </button>
    </div>
  );
}
0 Answers
Related