Reputation: 527
I want to integrate a feature that lets me track how long users spend in a specific react component (basically a section of the website). The website is build with react + nodejs + mysql. The only solution I can think of, is to send a post request for every minute a person spends in the component (by running a function in intervals when the component is loaded).
Is there a better way to achieve this, that doesn't involve 1000s of requests every minute? I don't want to track the statistics side-wide, only in a specific component.
Thank you.
Upvotes: 0
Views: 965
Reputation: 811
TYou could use react lifecycle methods to start timer and then send post on unmount https://reactjs.org/docs/state-and-lifecycle.html
Example something like this I have not tested code
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
start: new Date(),
end: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
postTimeToApi(this.state.start, this.state.end);
clearInterval(this.timerID);
}
tick() {
this.setState({
end: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.end.toLocaleTimeString()}.</h2>
</div>
);
}
}
Or maybe
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
start: new Date()};
}
componentWillUnmount() {
const end = new Date();
postTimeToApi(this.state.start, end);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.start.toLocaleTimeString()}.</h2>
</div>
);
}
}
Upvotes: 1