I am working on a React/Redux project and am attempting to remove a progress spinner that is getting stuck on my error page. I have confirmed my ClearAllSpinners action is working correctly, but I believe it is clearing the spinners prematurely, prior to the spinner showing up, since it is not working.
In my error page component, I have the following useEffect hook, which I have been trying to dispatch my action from anytime the page renders or there is a change to isAnySpinnerActive:
useEffect(() => {
dispatch(ClearAllSpinners());
}, [dispatch, isAnySpinnerActive]);
I know the action clears the spinners as intended since the following function sets a spinner and then clears it after 5 seconds successfully (this function was used solely as a test):
const addSpinner = () => {
dispatch(ShowSpinner('test-spinner'));
setTimeout(() => {
dispatch(ClearAllSpinners());
}, 5000);
};
Is there any other way I can dispatch my action anytime the error page is rendered and then again after any spinners may possibly appear, other than the useEffect hook I am using?
you are using the useEffect hook which triggers to call after a variable or statement has changed or triggered by default as componnetDidMount. you can read more about that here.
these variables or states must be added as your dependencies array to useEffect work properly as your expectation.
you want to call your dispatch action in your useEffect, it's okay, but when?
your snippet tells that dispatch ClearAllSpinners when your component did mount!!
you can do this with your status variable(which controlling Spinner visibility) like this:
useEffect(() => {
if(showSpinner) {
// triggered when showSpinner is true
setTimeout(() => {
dispatch(ClearAllSpinners());
}, 5000)
} else {
// triggered when your component did mount or when showSpinner was false!!
}
}, [dispatch, showSpinner])