Home > Software engineering >  show loading when fetching data react
show loading when fetching data react

Time:10-12

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

CodePudding user response:

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);
 };
}

CodePudding user response:

You've inversed no ?

  • 1: set spiiner to true

  • 2: Set spinner to false after api

    const [spinner, setSpinner] = useState(false);    
    
    function upload(){
     setSpinner(true);
    
     //some data to post the image
     fetch('my/API/Endpoint'), {
     method: 'post',
     body: body,
     }).then(function(data){
     setSpinner(false);
     };
    }
    

CodePudding user response:

You are setting the spinner state to true AFTER you're fetch is complete. It is then never set to false again. The behavior I'm expecting is that the text is not visible at first, then once the fetch is completed it is always visible.

You are going to want to set the spinner state to true in the upload function and then to false in promise resolver (the .then)

function upload(){
        //some data to post the image
        setSpinner(true)
        fetch('my/API/Endpoint'), {
          method: 'post',
          body: body,
        })
       .then(function(data){
          setSpinner(false);
         };
        }
  • Related