79457258

Date: 2025-02-21 11:40:17
Score: 0.5
Natty:
Report link
  const Upload = () => {
  const [fileName, setFileName] = useState('no file selected');
  const [resultText, setResultText] = useState('');
  const fileInputRef = useRef(null);

  const localIP = "myipv4address";
  const uploadUrl = `http://${localIP}:3000/upload`;

  const [userId, setUserId] = useState(null);


  useEffect(() => {
    const fetchUserData = async () => {
      const storedData = localStorage.getItem("auth");
      if (!storedData) return;

      const { email, password } = JSON.parse(storedData);
      try {
        const userResponse = await axios.get(
          `http://localhost:8080/users/byEmail/${email}`,
          {
            headers: { "Content-Type": "application/json" },
            auth: { username: email, password },
          }
        );

        setUserId(parseInt(userResponse.data.id));
        console.log(userResponse.data.id); // it prints 12, which is my user id, it works fine
      } catch (error) {
        console.error("error getting the user:", error);
      }
    };

    fetchUserData();
  }, []);

  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];
    if (!allowedTypes.includes(file.type)) {
      setFileName("invalid file!");
      event.target.value = "";
      return;
    }

    if (userId === null) {
      console.error("User ID invalid");
      return;
    }

    try {
      const formData = new FormData();
      formData.append("image", file);
      formData.append("userId", String(userId));

      const response = await fetch(uploadUrl, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) throw new Error("Error");

      const data = await response.json();
      setFileName(file.name);
      setResultText(`Image uploaded: ${data.imageUrl}`);
    } catch (error) {
      console.error("Error:", error);
      setFileName("Error");
      event.target.value = "";
    }
  };
return (
 <div className="qr-section">
      <p>or scan the qr code to upload from your phone:</p>
      <QRCodeComponent value={uploadUrl} />
    </div>

    <input
      id="file"
      type="file"
      accept="image/jpeg, image/jpg, image/png"
      onChange={handleFileChange}
      ref={fileInputRef}
    />
  </div>);};

Export default Upload;

Sorry if it has some errors, it is not the exact code, I edited a bit before posting it here So what I'm I doing wrong when trying to pass the userId to the server? As I said, in the server, if I try to console log it, it prints undefined

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Gabi Moldovan