So I am building this project using ChakraUI and ReactJS.
So in this UploadImage component, what I wanna do is, when you choose a file and then hit the Upload button, the spinner will load while the data is being fetched. After it is finished fetching the data, the loading is going to be false and it will render the component.
But currently it is rendering component initially and after you submit the file it renders the DisplayImage component.
So how to implement the spinner component properly?
My current code is the following:
function UploadImage() {
const [selectedFile, setSelectedFile] = useState(null);
const [error, setError] = useState(null);
const [inputImage, setInputImage] = useState(null);
const [outputImage, setOutputImage] = useState(null);
const [isSubmit, setIsubmit] = useState(false);
const [isLoading, setIsloading] = useState(true);
const fileUploadHandler = () => {
const fd = new FormData();
fd.append("file", selectedFile, selectedFile.name);
axios
.post(`/api/predict`, fd)
.then((res) => {
setIsubmit(true);
setInputImage(res.data.image);
setOutputImage(res.data.mask);
selectedFile(null);
setError(null);
setIsloading(false);
})
.catch((error) => {
console.log(error);
setSelectedFile(null);
setError(error.data);
});
};
const fileData = () => {
if (selectedFile) {
if (
selectedFile.type === "image/jpeg" ||
selectedFile.type === "image/png"
) {
return (
<div>
{error && <div>file too large!!</div>}
<Button
colorScheme='teal'
size='sm'
onClick={() => fileUploadHandler()}
>
Upload!
</Button>
</div>
);
} else {
return (
<div>
<h4>Please choose an image to upload</h4>
</div>
);
}
} else {
return (
<div>
<h4>Choose Photos</h4>
</div>
);
}
};
return (
<div>
<input type='file' onChange={(e) => setSelectedFile(e.target.files[0])} />
{fileData()}
{isSubmit && isLoading === false ? (
<DisplayImage inputImage={inputImage} outputImage={outputImage} />
) : (
<Spinner />
)}
</div>
);
}
export default UploadImage;