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