I have a fetch call where users can upload an image and then post it.
However, I want to show the user when the image is being posted, with a loader. My issue is that my loader is always shown. The text something is loading is always shown. I just want to show the text while the request is pending. can I please get some help with that=
export default function ImageUpload() {
const [spinner, setSpinner] = useState(false);
function upload(){
//some data to post the image
fetch('my/API/Endpoint'), {
method: 'post',
body: body,
})
.then(function(data){
setSpinner(true);
};
}
return (
<>
<input type="file"/>
<input onClick={upload}/>
{spinner && (
<p>something is loading</p>
)}
</>
);
}
I do want to point out that the logic behind posting and fetching the image does work, I do get status 200! Its only the loading message that does not work
The method you have used will always set the spinner to true..bcuz .then is always executed after the fetch promise resolves...
You need to set the spinner to true just before the fetch is called and make the spinner false in .then.... you need something like this
const [spinner, setSpinner] = useState(false);
function upload(){
setSpinner(true);
//some async process
fetch('my/API/Endpoint'), {
method: 'post',.0
body: body,
}).then(function(data){
setSpinner(false);
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With