skip to Main Content

It works when I stay on this page. However, when I switch to another tab and come back while the api is processing, setLoading(false) is never triggered.

How can I fix this?

const [loading, setLoading] = useState(false);

useEffect(() => {
  setLoading(!!window.sessionStorage.getItem("isButtonDisabled");
}, []);

useEffect(() => {
   console.log(loading);
}, [loading]);

const showReport = () => {
  setLoading(true);
  window.sessionStorage.setItem("isButtonDisabled", true);
  return axios({
    url: 'api/report/getdata',
    method: 'GET',
    responseType: 'blob'
  }).then(() => {
    window.sessionStorage.setItem("isButtonDisabled", false);
    setLoading(false);
  });
};    

2

Answers


  1. You might want to use .finally() because .then() is triggered only if the promise finishes successfully. More details about finally in Mozilla Docs.

    To resolve the issue, you might also want to use useEffect() cleanup to call a callback to stop the loading whenever the component gets unmounted.

    Login or Signup to reply.
  2. ReportLoadingPanel is showing forever because:

    1. window.sessionStorage.getItem("isButtonDisabled") always returns a string, so, conversions to boolean: !!'true' is equals to true and !!'false' is equals to true also. The correct check would look like this: window.sessionStorage.getItem("isButtonDisabled") === 'true'
    2. Call to the API would be unsuccessful, but you only handle successful cases using .then(), to solve this, add a call of .catch() after .then() and call setLoading(false) and window.sessionStorage.setItem("isButtonDisabled", false) there too, or, as mentioned above, you can use .finally(), as it is being fired regardless Promise is resolved or rejected.
    3. Delete the first useEffect hook and move logic from there to useState hook:
    const [loading, setLoading] = useState(() => window.sessionStorage.getItem("isButtonDisabled") === 'true')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search