Browse Source

Switch to useing a timeout instead of an interval b/c useEffect refires every update anyway

Kirk Trombley 5 years ago
parent
commit
8f08c4f336
1 changed files with 11 additions and 11 deletions
  1. 11 11
      client/src/App.js

+ 11 - 11
client/src/App.js

@@ -1,12 +1,6 @@
 import React, { useState, useEffect, useRef } from 'react';
 import styles from './App.module.css';
 
-const getUsers = async () => {
-  const res = await fetch("https://hiram.services/teamspeak/api");
-  const { users } = await res.json();
-  return users;
-}
-
 const UserList = React.memo(({ users }) => (
   <div className={styles.userList}>
     <span className={styles.title}>TeamSpeak Server Status</span>
@@ -23,13 +17,13 @@ const updateVelocities = (el, bounding) => {
   if (el.offsetLeft <= 5 && vx < 0) {
     vx = -1 * vx;
   }
-  if ((el.offsetLeft + el.offsetWidth) >= (bounding.offsetWidth - 5)) {
+  if ((el.offsetLeft + el.offsetWidth) >= (bounding.offsetWidth - 20)) {
     vx = -1 * vx;
   }
   if (el.offsetTop <= 5 && vy < 0) {
     vy = -1 * vy;
   }
-  if ((el.offsetTop + el.offsetHeight) >= (bounding.offsetHeight - 5)) {
+  if ((el.offsetTop + el.offsetHeight) >= (bounding.offsetHeight - 10)) {
     vy = -1 * vy;
   }
 }
@@ -39,19 +33,25 @@ export default () => {
   const bounceRef = useRef(null);
   const [{x, y}, setPos] = useState({ x: 0, y: 0 });
   const [users, setUsers] = useState([]);
+
   useEffect(() => {
-    const update = () => {  getUsers().then(setUsers) };
+    const update = async () => { 
+      const res = await fetch("https://hiram.services/teamspeak/api");
+      const { users } = await res.json();
+      setUsers(users);
+    };
     const interval = setInterval(update, 30000);
     update();
     return () => clearInterval(interval);
   }, []);
+
   useEffect(() => {
     const update = () => { 
       updateVelocities(bounceRef.current, boundRef.current);
       setPos({x: x + vx, y: y + vy}) 
     };
-    const interval = setInterval(update, 30);
-    return () => clearInterval(interval);
+    const interval = setTimeout(update, 30);
+    return () => clearTimeout(interval);
   }, [x, y]);
 
   return (