I have this function that adds claps to a post. I don't want to add a clap with every clap because that would be insane on my mysql server, not to mention the http requests and re-renders. Instead, I want to let the claps add up a bit and only if the user stops adding claps for a few seconds, then add the claps to the database. So my function is storing the claps in state properly, but it is running the function every time and never clearing the timeout.
let sendClapsToDB
_clapForPost = (postId) => {
clearTimeout(sendClapsToDB)
setClaps(() => claps + 1)
sendClapsToDB = setTimeout(() => {
_addClapsToPost(claps, postID)
}, 5000)
}
Does anyone know how to do this properly. I am using React Native and fetch. The _clapForPost function is being called every time a user presses on a button.
If you are using a class component you can try something like this.
import React from "react";
class App extends React.Component {
state = {claps: 0}
timeout = null;
sendClap = () => {
this.setState({claps: this.state.claps + 1})
if(!this.timeout){
this.timeout = setTimeout(() => {
console.log("Send claps", this.state.claps);
clearTimeout(this.timeout);
this.timeout = null;
}, 3000)
}
}
render(){
console.log(this.state.claps);
return <button onClick={this.sendClap}>Clap</button>
}
}
export default App;
Im clearing the timer as it runs and re-initializing in the next state update. Also need to clear the timer when the component unmounts.
If you are using functional component with hooks, you can try something like
import React, {useState, useRef} from "react";
export default () => {
const [claps, setClaps] = useState(0);
const clapsRef = useRef(0);
clapsRef.current = claps;
const timeout = useRef(null);
const sendClap = () => {
setClaps(claps + 1);
if(!timeout.current){
timeout.current = setTimeout(() => {
console.log("Send claps", clapsRef.current);
clearTimeout(timeout.current);
timeout.current = null;
}, 3000)
}
}
console.log(claps);
return <button onClick={sendClap}>Clap</button>
}
Here I'm using useState to re-render the component and useRef to capture the latest state for timeout to get the latest state reference.