Home > Software engineering >  React change components on setInterval
React change components on setInterval

Time:10-05

for the first 3 seconds it should show LoadingActive component, after that it should dissapear and show LoadingFailed and on Button press it should again show LoadingActive 3s and than LoadingFailed. How can i do the part where onPress the cycle repeats one more time?

export function Loading() {
    const [showComponent, setShowComponent] = React.useState(false);

React.useEffect(() => {
    setInterval(() => {
        setShowComponent(!showComponent);
    }, 3000);
}, []);

return (
        <View>
            {showComponent && <LoadingFailed />}
            {!showComponent && <LoadingActive />}
        </View>
);
}

function LoadingActive() {
    return (
    <View>
        <Text>
            Loading
        </Text>
    </View>
);
}

function LoadingFailed() {
    return (
    <View>
        <Text>
            Failure
        </Text>
        <Button onPress={} title='RETRY' /> //On press should again show  `LoadingActive` 3s and than `LoadingFailed`
    </View>
);
}

CodePudding user response:

Since you need a single timeout every time use setTimeout and let useEffect initialize it every time that the loading state changes to true:

const { useState, useEffect } = React;

function Loading() {
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let timeout;
    
    if(loading) {
      setTimeout(() => {
        timeout = setLoading(false);
      }, 3000);
    }
    
    return () => {
      clearTimeout(timeout);
    }
  }, [loading]);

  return (
    <div>
      {loading 
        ? <LoadingActive /> 
        : <LoadingFailed reload={() => setLoading(true)} />
      }
    </div>
  );
}

function LoadingActive() {
  return (
    <div>
      Loading
    </div>
  );
}

function LoadingFailed({ reload }) {
  return (
    <div>
      <button title='RETRY' onClick={reload}>Retry</button>
    </div>
  );
}

ReactDOM
  .createRoot(root)
  .render(<Loading />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>

  • Related