time spent on a webpage
hi Team, i am working on a project where in i need to find the time spent on a webpage, and i also need to store the value and send it to server for analytics purpose (analytics code is not present) here is my code.import React, { Component } from 'react';
import TimeMe from 'timeme.js';
class MyComponent1 extends Component {
constructor(props) {
super(props)
this.initialize = this.initialize.bind(this);
this.count = this.count.bind(this);
}
componentDidMount() {
this.initialize();
console.log("mount1");
}
initialize() {
// Initialize library and start tracking time
TimeMe.initialize({
currentPageName: this.props.pageName, // current page
idleTimeoutInSeconds: 0 // seconds
});
}
count() {
// Retrieve time spent on current page
TimeMe.stopTimer(this.props.pageName);
let timeSpentOnPage = TimeMe.getTimeOnPageInSeconds(this.props.pageName);
let timeSpentSofar = parseInt(localStorage.getItem('TimeSpentOnMyGame')) + timeSpentOnPage;
localStorage.setItem(TimeSpentOnMyGame, timeSpentSofar);
}
componentWillUnmount() {
this.count();
}
render() {
console.log("mount1rendered");
return (
<div>
{/* Your component's UI */}
<p>Time spent on site MyComponent1:</p>
</div>
);
}
}
export default MyComponent1; issue is : like wise i have one more component , MYComponent2, so when ever i am switching between two routes, for the current route , the componentwillunmount method is exitting executed , and the "TimeSpentOnMyGame" value is getting multiple times. can i have some help here please, i have been running around this from last three days
6 Replies
I'm so confused why you can't use analytics for this?
i am not quite sure about that,but i need to solve this problem can you help me whats the problem in my code please
I have no idea
no worries
🐟 y
You are best off putting this into a codesandbox