Explorar el Código

Converting timer to use hooks

Kirk Trombley hace 5 años
padre
commit
5d56ca25c0

+ 3 - 1
client/src/components/screens/game-panel.component/guess-pane.component.jsx

@@ -18,7 +18,9 @@ export default ({
       justifyContent:"space-around",
     }}
   >
-    <RoundTimer style={{ flex: 1 }} seconds={roundSeconds} onTimeout={onTimeout} />
+    <div style={{ display: "flex", justifyContent: "center", alignItems: "center", flex: 1 }}>
+      <RoundTimer seconds={roundSeconds} onTimeout={onTimeout}/>
+    </div>
     <div style={{ height: "100%", margin: "5px", flex: 6 }}>
       <ClickMarkerMap onMarkerMoved={onSelectPoint} />
     </div>

+ 13 - 40
client/src/components/screens/game-panel.component/round-timer.component.jsx

@@ -1,45 +1,18 @@
-import React from "react";
+import React, { useEffect, useState } from "react";
 import ms from "pretty-ms";
 
-class RoundTimer extends React.Component {
-  constructor(props) {
-    super(props);
-    const { seconds } = this.props;
-    this.state = {
-      running: false,
-      remaining: seconds,
+export default ({ seconds, onTimeout }) => {
+  const [remaining, setRemaining] = useState(seconds);
+  useEffect(() => {
+    const countDown = () => {
+      setRemaining(remaining - 1)
+      if (remaining <= 0) {
+        onTimeout();
+      }
     }
-  }
+    const timer = setInterval(countDown, 1000);
+    return () => { clearInterval(timer) };
+  });
 
-  componentDidMount() {
-    this.timer = setInterval(() => this.countDown(), 1000);
-  }
-
-  componentWillUnmount() {
-    clearInterval(this.timer);
-  }
-
-  countDown() {
-    const { remaining } = this.state;
-    
-    this.setState({ remaining: remaining - 1 });
-
-    if (remaining <= 0) { 
-      const { onTimeout } = this.props;
-      clearInterval(this.timer);
-      onTimeout();
-    }
-  }
-  
-  render() {
-    const { remaining } = this.state;
-    const { style } = this.props;
-    return (
-      <div style={{ display: "flex", justifyContent: "center", alignItems: "center", ...style }}>
-        {remaining > 0 ? <p>Time: {ms(remaining * 1000)}</p> : <p>Time's up!</p>}
-      </div>
-    );
-  }
+  return remaining > 0 ? <p>Time: {ms(remaining * 1000)}</p> : <p>Time's up!</p>
 }
-
-export default RoundTimer;

+ 1 - 1
client/src/components/screens/pre-game.component/pre-game.component.jsx

@@ -25,7 +25,7 @@ const PreGame = ({ initPlayerName, onGameJoined }) => {
   const onChangeGameId = ({ target }) => setGameId(target.value.trim());
   const onCreateGame = async () => {
     setLoading(true);
-    const gameId = await createGame(playerName, 30);
+    const gameId = await createGame(playerName, 300);
     onGameJoined({ gameId, playerName });
   };
   const cannotCreateGame = !playerName || playerName.length === 0;