'Undefined error message in component React
I'm attempting to upload an image to the Cloudinary website, and then continue on to display them on my webpage, however I keep receiving errors in my code. This is the error I'm receiving.

And this is my current code.
// ImageDisplay.js
import React, { useState } from "react";
import axios from "axios";
export default function ProfileImage() {
const [values, setValues] = useState({
imagePreviewUrl: "",
picFile: null,
});
let fileInput = React.createRef();
// Activates user file input to set div
const editProfilePic = () => {
fileInput.current.click();
};
// Handles the image that was input by user
const handleImageChange = (e) => {
e.preventDefault();
let reader = new FileReader();
let inFile = e.target.files[0];
reader.onloadend = () => {
setValues({ ...values, picFile: inFile, imagePreviewUrl: reader.result });
};
reader.readAsDataURL(inFile);
};
// Call the API Backend, will describe this later
const handleSubmit = async () => {
// response stores the response back from the API
response = await axios.post(`/storage/upload`, form_data).catch((error) => {
alert(
"Error occurred while uploading picture, try uploading a smaller image size or try again later."
);
return;
});
};
return (
<div>
<div onClick={() => editProfilePic()}>
<input
type="file"
accept="image/*"
onChange={handleImageChange}
ref={fileInput}
/>
<img src={imagePreviewUrl} alt="..." style={{ objectFit: "cover" }} />
</div>
<button onclick={handleSubmit}>Submit</button>
</div>
);
}
Solution 1:[1]
The problem is simple.
You have undeclared variables. response, from _data, imagePreviewUrl.
Apparently you want to upload images to the storage using axios by post, I recommend you read this examples https://www.codegrepper.com/code-examples/javascript/axios+file+upload
Solution
First change the function handleSubmit to this
const handleSubmit = async () => {
//Solution fixe form_data adding your picFile to FormData
var formData = new FormData();
formData.append("image", values.picFile);
// response stores the response back from the API
//Solution fixed error response applying const to variable response
const response = await axios.post(`/storage/upload`, form_data).catch((error) => {
alert(
"Error occurred while uploading picture, try uploading a smaller image size or try again later."
);
return;
});
};
Change the imagePreviewUrl replace this
<img src={imagePreviewUrl} alt="..." style={{ objectFit: "cover" }} />
Solution:
<img src={values.imagePreviewUrl} alt="..." style={{ objectFit: "cover" }} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alexander ferreras |
