Skip to content

Commit

Permalink
fix timer state, feat #18
Browse files Browse the repository at this point in the history
  • Loading branch information
PatheticMustan authored Mar 6, 2022
1 parent 0f2dab5 commit 826dd69
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
24 changes: 17 additions & 7 deletions Components/OneUse/Timer.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,43 @@ import {
} from "react-native";
import BoolButton from "../Buttons/BoolButton.js";

import { setKeyPair, setDefault, selectID } from "../../Redux/Features/dataSlice.js";
import { setKeyPair, setDefault, selectID, selectBlendedID, consumeBlend } from "../../Redux/Features/dataSlice.js";
import { useDispatch, useSelector } from "react-redux";

export default function Timer(props) {
const dispatch = useDispatch();
const [isEnabled, setEnabled] = useState(false);
const [seconds, setSeconds] = useState(0);

// set default values
dispatch(setDefault([props.id, 0]));

const reduxTime = useSelector(selectID(props.id));
// https://github.com/rebels2638/ScoutingApp2022/issues/18
const blendedTime = useSelector(selectBlendedID(props.id));

const [isEnabled, setEnabled] = useState(false);
const [seconds, setSeconds] = useState(reduxTime);
if (blendedTime !== null) {
setSeconds(blendedTime);
dispatch(consumeBlend(props.id));
// stop timer on match reset/load
setEnabled(false);
dispatch(setKeyPair(["TimerClicked", false]));
}

// when toggling the timer, save the time to redux
const toggleTimer = () => {
setEnabled(v => !v);
dispatch(setKeyPair([props.id, seconds]));
}

useEffect(() => {
const timerInterval = setInterval(() => {
if (isEnabled) setSeconds(oldSeconds => oldSeconds + 1);
}, 1000);

// callback when isEnabled ends
return () => { clearInterval(timerInterval) };
return () => clearInterval(timerInterval);

// run when isEnabled updates
// run when the timer is started/stopped
}, [isEnabled]);

return (
Expand Down
2 changes: 1 addition & 1 deletion Components/Utility/CustomTextBox.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default function CustomTextBox(props) {

if (blendedText !== null) {
setText(blendedText);
dispatch(consumeBlend(props.id))
dispatch(consumeBlend(props.id));
}

// keep redux text updated after a 500ms delay of not editing
Expand Down

0 comments on commit 826dd69

Please sign in to comment.