Skip to content

Commit 69caece

Browse files
baileydunningdawsontoth
authored andcommitted
fix: Refactor user tracking actions in Datadog integration
1 parent 38937de commit 69caece

File tree

1 file changed

+29
-26
lines changed

1 file changed

+29
-26
lines changed

src/integrations/datadog/datadog.ts

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -77,47 +77,50 @@ export function useOnRouteLoadTracker() {
7777
return;
7878
}
7979
if (user && !isLocalUser(user)) {
80-
datadogRum.setUser({
81-
id: user.id,
82-
name: [user.firstname, user.lastname].filter(excludeFalsy).join(' ') || undefined,
83-
email: user.email,
84-
});
85-
86-
// First time vs return visit action
87-
if (localStorage.getItem('hasVisitedBefore')) {
88-
datadogRum.addAction('return_visit');
89-
} else {
90-
datadogRum.addAction('first_time_visit');
91-
localStorage.setItem('hasVisitedBefore', 'true');
92-
}
93-
80+
datadogRum.setUser({
81+
id: user.id,
82+
name: [user.firstname, user.lastname].filter(excludeFalsy).join(' ') || undefined,
83+
email: user.email,
84+
});
9485
} else {
9586
datadogRum.clearUser();
9687
}
9788
}, [user]);
9889
}
9990

100-
export function loginSuccessDatadogAction(data: { id: string; email: string; firstname: string; lastname: string }) {
91+
export function loginSuccessDatadogAction(data: { id: string; email: string; firstname: string; lastname: string; }) {
10192
if (!enabled) return;
10293

103-
// Time between logins
104-
const lastLogin = localStorage.getItem('lastLoginTimestamp');
94+
datadogRum.setUser({
95+
id: data.id,
96+
email: data.email,
97+
name: [data.firstname, data.lastname].filter(Boolean).join(' ') || undefined,
98+
});
99+
100+
// First vs return login (per user)
101+
const hasLoggedInKey = `hasLoggedInBefore:${data.id}`;
102+
const hasLoggedInBefore = !!localStorage.getItem(hasLoggedInKey);
103+
104+
if (hasLoggedInBefore) {
105+
datadogRum.addAction('return_login');
106+
} else {
107+
datadogRum.addAction('first_time_login');
108+
localStorage.setItem(hasLoggedInKey, 'true');
109+
}
110+
111+
// Time between logins (per user)
112+
const lastLoginKey = `lastLoginTimestamp:${data.id}`;
113+
const lastLogin = localStorage.getItem(lastLoginKey);
105114
const now = Date.now();
106-
115+
107116
if (lastLogin) {
108117
const seconds = Math.floor((now - Number(lastLogin)) / 1000);
109118
if (!Number.isNaN(seconds) && seconds >= 0) {
110-
datadogRum.addAction('login_time_gap', { seconds });
119+
datadogRum.addAction('login_time_gap', { value: seconds });
111120
}
112121
}
113122

114-
localStorage.setItem('lastLoginTimestamp', String(now));
115-
116-
datadogRum.setUser({
117-
id: data.id,
118-
email: data.email,
119-
name: [data.firstname, data.lastname].filter(Boolean).join(' ') || undefined,
120-
});
123+
localStorage.setItem(lastLoginKey, String(now));
121124

122125
datadogRum.addAction('login_success', { userId: data.id });
123126
}

0 commit comments

Comments
 (0)