Home > database >  how to show loading bar for few seconds
how to show loading bar for few seconds

Time:10-21

I want to show the progress bar for 500ms even if its 100%loaded. Current scenario: sometimes the data is arrived so fast the progressbar appears and disappears very quickly. User sometime misses to see it even if it was shown.

tried to use setTimeout(() => ,500) // but didnt work out.

Any logical hints appreciated.

class ABC extends React.Component {
  render() {
    return (
    <>
        {state === Running && (
          <ProgressBar
           minValue={0}
           maxValue={100}
           progress={percentage}
           />
        )}
    </>
    );
  }
}
class ProgressBar extends React.Component {
  render() {
    let percentage = (this.props.progress - this.props.minValue) / (this.props.maxValue - this.props.minValue);
    percentage =  Math.max(Math.min(percentage , 1), 0);
    const fillstyle = { width: (percentage * 100)   "%" };
    return (
      <div className="progressbar" style={this.props.style}>
        <div className="progressbar--fill" style={fillstyle}></div>
      </div>);
}

CodePudding user response:

The best way to demonstrate that would be a React functional component with useEffect that starts a timer

Like this:

const ABC = () => {
  const [isTimerRunning, setIsTimerRunning] = React.useState(true);

  React.useEffect(() => {
    let canceled = false;
    setTimeout(() => { 
      if (!canceled) {
        setIsTimerRunning(false)
      }
    }, 500);
    return () => canceled = true;
  }, []);

  return (isTimerRunning || Running) ? (
          <ProgressBar
           minValue={0}
           maxValue={100}
           progress={50}
           />
        ) : null;
}

The cancelation of the timeout is a best practice from React. your component might get un-mounted before the timer executed, and once it's executed it will try to set the state on an unmounted component, leading to an error on react. that's why it's best to make sure you return a function (Will be called by React on unmount) that cancels the "future" execution.

  • Related