Best practice of using SetInterval without classes in React - reactjs

As part of my React learning, I wrote a simple timer. After the timer reaches the end (with useEffect) it doesn't enter the function buttonString after the useEffect hook, because the measurement isn't part of the application state, so the HTML isn't rendered.
What is the correct way to handle such a situation? Inserting the setInterval's id to a hook sounds me incorrect, but I'm not sure.
Thank you
The code:
var measurement;
export default function App() {
const [timeLeft, setTimeLeft] = useState("10000");
useEffect(() => {
if (timeLeft<500) {
clearInterval(measurement);
measurement = null;
}
});
function buttonString() {
console.log('[buttonString] measurement:' + measurement);
return ((measurement!==null) && (measurement!==undefined)) ? "reset" : "Click To Start";
}
function timeLeftAsString() {
let duration = moment.duration(timeLeft);
let mins = duration.minutes();
let secs = duration.seconds();
return mins + " : " + secs;
}
function startMeasurement() {
clearInterval(measurement);
var timeStart = moment().add(11, 's');
measurement = setInterval(() => {
setTimeLeft(moment(timeStart).diff());
}, 500);
}
return (
<div className="App">
<p> {timeLeftAsString()} </p>
<Button variant="primary" size="lg" className="Button" onClick={() => {
startMeasurement();
}}>
{buttonString()}
</Button>
</div>
);
}

Related

how to create a timer inside hooks on Reactjs?

I am a starter at React! Started last week ;)
My first project is to create a timer which has a reset function and a second count function.
The reset function is working great, however the timer does not. Which is the best way to do it? It should increase +1s on variable 'second' according to the setTimeout() function.
Is it possible to create a loop on Hooks? I tried to do with the code below, but the page goes down, I think it is because the infinite loop that the code creates;
const [hour, setHour] = useState(4)
const [minute, setMinute] = useState(8)
const [second, setSecond] = useState(12)
// methods
const setTime = (value: string) => {
if (value === 'reset'){
setHour(0);
setMinute(0);
setSecond(0);
}
}
const startTime = () => {
while (second < 60){
setTimeout(() => {
setSecond(second + 1);
}, 1000);
}
};
<div className="d-flex justify-content-center">
<MainButton
variantButton="outline-danger"
textButton="RESET"
functionButton={() => setTime('reset')}
/>
<MainButton
variantButton="outline-success"
textButton="START"
functionButton={() => startTime()}
/>
</div>
Welcome to React! You're very close. setTimeout and setInterval are very similar and for this you can simply use setInterval. No need for a while() loop! Check out this working Sandbox where I created a simple React Hook that you can use in your App.js
https://codesandbox.io/s/recursing-hooks-jc6w3v
The reason your code got caught in an infinite loop is because startTime() function has stale props. Specifically, the second variable is always 0 in this case, because when you defined startTime() on component mount, second was 0. The function doesn't track it's incrementing.
To resolve this issue, instead of:
setSecond(second + 1);
Try using:
setSecond((s) => s += 1);
EDIT* There are many good articles on React Stale Props. Here's one that's helpful: https://css-tricks.com/dealing-with-stale-props-and-states-in-reacts-functional-components/
EDIT** Additional inline examples of the exact issue:
Two changes I would make:
Use setInterval instead of setTimeout in a while() loop.
Create a useTimer hook which handles your timer logic.
App.js
import "./styles.css";
import useTimer from "./useTimer";
export default function App() {
const [setTime, startTime, stopTime, hour, minute, second] = useTimer();
return (
<div>
<div className="d-flex justify-content-center">
<button onClick={() => setTime("reset")}>RESET</button>
<button onClick={startTime}>START</button>
<button onClick={stopTime}>STOP</button>
</div>
<br />
<div>
Hour: {hour} <br />
Minute: {minute} <br />
Second: {second} <br />
</div>
</div>
);
}
useTimer.js
import { useState } from "react";
const useTimer = () => {
const [hour, setHour] = useState(4);
const [minute, setMinute] = useState(8);
const [second, setSecond] = useState(12);
const [timer, setTimer] = useState();
// methods
const clearTimer = () => clearInterval(timer);
const setTime = (value) => {
if (value === "reset") {
setHour(0);
setMinute(0);
setSecond(0);
}
};
const startTime = () => {
if (timer) clearTimer();
const newInterval = setInterval(() => {
setSecond((s) => (s += 1));
}, 1000);
setTimer(newInterval);
};
const stopTime = () => clearTimer();
return [setTime, startTime, stopTime, hour, minute, second];
};
export default useTimer;

Import function from another page

I need to call function resetToken() from another page when i click on button.
resetToken() should change useState to generate new code. I don't know how to import this function to another page and use it.
I have import
import Captcha from '../../../components/Captcha/Captcha'; and displayed with <Captcha/> in return( ... )
So when i click on button I need to call function resetToken() to generate new code or call again import because I have in <Captcha/>
React.useEffect(() => {
resetToken();
},[]);
This code is Captcha.jsx
import React from 'react';
import './Captcha.css';
function Captcha({statusOfCaptcha}){
const [status, setStatus] = React.useState(undefined);
const [code, setCode] = React.useState(undefined);
const [text, setText] = React.useState("");
const [seconds, setSeconds] = React.useState(120);
function resetToken(){
//generate code
var codeGenerated = "";
var possible = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789";
for (var i = 0; i < 6; i++){
codeGenerated += possible.charAt(Math.floor(Math.random() * possible.length));
}
setCode(codeGenerated);
//reset every 120 second
setInterval(function(){
var codeGenerated = "";
var possible = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789";
for (var i = 0; i < 6; i++){
codeGenerated += possible.charAt(Math.floor(Math.random() * possible.length));
}
setCode(codeGenerated);
setSeconds(120);
setStatus(undefined);
setText("");
}, 120000);
const interval = setInterval(() => {
setSeconds(seconds => seconds - 1);
}, 1000);
return () => clearInterval(interval);
}
React.useEffect(() => {
resetToken();
},[]);
function checkCaptcha(e){
if(e === code){
setStatus(true);
statusOfCaptcha(true);
} else{
setStatus(false);
statusOfCaptcha(false);
}
}
return (
<div className='captcha'>
<div className="background">
<p onCopy={(e) => e.preventDefault()} className="unselectable">{code}</p>
<a>{seconds}</a>
</div>
<div className='input-captcha'>
<input type="text" placeholder="Zadejte kód" value={text} onChange={(e) => {checkCaptcha(e.target.value); setText(e.target.value)}}/>
{status === false && (<i class='bx bx-x text-color-red'></i>)}
{status === true && (<i class='bx bx-check text-color-green'></i>)}
</div>
</div>
)
}
export default Captcha;
This code is index.jsx
import React from 'react'
import Captcha from '../../../components/Captcha/Captcha';
function Index() {
function change(){
//here i need to call function from Captcha.jsx - resetToken();
}
return (
<div>
<Captcha statusOfCaptcha={resCaptchaData}/>
<button onclick={change}>Reset captcha code</button>
</div>
)
}
export default Index
It would be better to use a custom hook, to store your state, and resetToken function, So you can use it in multiple places.
For more resources about custom hooks.
https://reactjs.org/docs/hooks-custom.html
You can do this in several ways
for example you can use state manager like context api or redux.
In order to have access to your states or functions everywhere and in all pages and components
Or you can put the resetToken function in the parent component and have access to it in the child components.
export const ParentComponent = (children) => {
function resetToken {
....
}
return (
<Recapcha resetToken={resetToken} />
)
}
const Recapcha = ({resetToken}) => {
return (...)
}

Why is the min state getting updated 2 times instead of only once?

Why is the min state getting updated in the multiples of two instead of just updating by one after every 59 seconds? How do I fix it?
import { useRef, useState } from "react";
export const Timer = () => {
const [second, setSecond] = useState(0);
const [min, setMin] = useState(0);
const watch = useRef(null);
const startTimer = () => {
watch.current = setInterval(() => {
setSecond((value) => {
if (value === 59) {
setSecond(0);
setMin((v) => v + 1);
}
return value + 1;
});
}, 1000);
};
return (
<div>
<h1>
{min}:{second}{" "}
</h1>
<button onClick={startTimer}>Start</button>
<button onClick={() => clearInterval(watch.current)}>Pause</button>
<button
onClick={() => {
setSecond(0);
return clearInterval(watch.current);
}}
>
Reset
</button>
</div>
);
};
This is the component as a whole. I am new to react so please help.

how to clearInterval if any previous setInterval is running in REACT?

I want to make a Reverse Countdown Timer in which that has an input field and when I type a number and press the "Enter" key, the countdown starts. but the problem is when I want to stop the previous interval and starts new interval with new number and press Enter key, it runs parallel with previous one.
I'm pretty new to react, can somebody give me some advice to fix the problem ?
import React, {useState} from "react";
const App = () => {
const [ctime, setctime]=useState();
const enterdown=(value)=>{
clearInterval(interval);
setctime(value);
var interval = setInterval(()=>{
value--;
if(value==0){
clearInterval(interval);
}
setctime(value);
},1000)
}
return (
<div className="wrapper">
<div id="whole-center">
<h1>
Reverse countdown for<input id="timeCount" onKeyDown={(e)=>{e.key == "Enter" ?(enterdown(e.target.value)) :null}} /> sec.
</h1>
</div>
<div id="current-time">{ctime}</div>
</div>
)
}
export default App;
use this const interval = useRef(); instead of var interval
Full working code:
Also codesandbox link: https://codesandbox.io/s/zealous-monad-thhrvz?file=/src/App.js
const App = () => {
const interval = useRef();
const [ctime, setctime] = useState();
const enterdown = (value) => {
clearInterval(interval.current);
setctime(value);
interval.current = setInterval(() => {
value--;
if (value == 0) {
clearInterval(interval.current);
}
setctime(value);
}, 1000);
};
return (
<div className="wrapper">
<div id="whole-center">
<h1>
Reverse countdown for
<input
id="timeCount"
onKeyDown={(e) => {
e.key == "Enter" ? enterdown(e.target.value) : null;
}}
/>{" "}
sec.
</h1>
</div>
<div id="current-time">{ctime}</div>
</div>
);
};
The interval variable gets created each time the App function is run.
Which is in this case each time you press Enter.
It can be fixed by placing it out of the App function.
let interval;
const App = () => {
const [ctime, setctime] = useState();
const enterdown = (value) => {
clearInterval(interval);
setctime(value);
interval = setInterval(() => {
value--;
if (value === 0) {
clearInterval(interval);
}
setctime(value);
}, 1000);
};
// ...
Another solution would be using useRef

setState inside setTimeout react hooks

I am currently trying to build a rock-paper-scissor and what I intend to achieve are this logic:
after the start button clicked, a player has 3seconds to pick a weapon, if not, a random weapon will be picked for the player.
The problem:
When I picked a weapon under the 3seconds, it works just fine. But, when I intentionally let the setTimeout triggered, it is not updating the state automatically. I suspected the if conditions are not met, but I don't know why that happen.
Here is the code snippet:
//custom hooks//
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const weapons= ['rock', 'weapon', 'scissors']
const App = () => {
const [p1Weapon, setp1Weapon] = useState("");
const prevWeapon = usePrevious(p1Weapon);
const getPlayerTimeout = (playerRef, setPlayer, time) => {
setTimeout(() => {
if (playerRef === "") {
setPlayer(weapons[Math.floor(Math.random() * weapons.length)]);
}
}, time);
};
const startGame = () => {
getPlayerTimeout(prevWeapon, setp1Weapon, 3000);
}
return (
...
<div>
<button
className="weaponBtn"
onClick={() => {
setp1Weapon("rock");
}}
>
rock
</button>
<button className="weaponBtn" onClick={() => setp1Weapon("paper")}>
paper
</button>
<button className="weaponBtn" onClick={() => setp1Weapon("scissors")}>
scissor
</button>
<button type="button" onClick={startGame}>
Start!
</button>
</div>
)
Thanks!
if all you want to do is set a state after x time you can do this very easily like this
this.setState({isLoading: true},
()=> {window.setTimeout(()=>{this.setState({isLoading: false})}, 8000)}
);
this should set the value of isLoading to false after 8 seconds.
I hope it helps

Resources