I am trying to count the number of times a button is pressed within a second.
It's working, for the most part, it tracks it and outputs it.
But the problem is that it outputs the button press count from the last second instead of the current second.
I think it would work if the order was reversed somehow, how do I fix up this function? Thanks.
const [clicksPerSecond, setClicksPerSecond] = useState(0);
const [tempCounter, setTempCounter] = useState(0);
const [tempCounter2, setTempCounter2] = useState(0);
const { setCounter, counter } = useContext(CountContext);
useEffect(() => {
console.log(tempCounter);
if (tempCounter != 0) {
if (tempCounter == 1) {
setTimeout(() => {
setClicksPerSecond(tempCounter2);
setClicksPerMinute(tempCounter2 * 60);
setTempCounter(1);
console.log('Clicks per second final: ' tempCounter2);
}, 1000)
} else {
setTempCounter2(tempCounter);
console.log('Clicks per second: ' tempCounter);
}
}
setTempCounter(tempCounter 1);
}, [counter])
return (
<View style={[styles.container, { backgroundColor: colors.background }]}>
<View elevation={7.5} style={{ backgroundColor: colors.background, borderRadius: 500 }}>
<TouchableOpacity
onPress={() => setCounter(counter 1)}
style={[styles.counterButton, { backgroundColor: colors.primary, borderColor: colors.container, borderWidth: 0 }]}>
<Text></Text>
<Text style={{ fontSize: 60 }}>{counter}</Text>
<Text>{clicksPerSecond} CPS</Text>
</TouchableOpacity>
</View>
</View>
);
}
CodePudding user response:
You can instead just increment the count and decrement it after a second.
export default function App() {
const [clicks, setClicks] = React.useState(0);
const onClick = () => {
setClicks((c) => c 1);
setTimeout(() => setClicks((c) => c - 1), 1000);
};
return (
<div>
<button onClick={onClick}>Click me</button>
<p>Clicked {clicks} times</p>
</div>
);
}
You will also need to track if the component is unmounted before decrement, which I think you can do using refs. Example