matomo-org / matomo

Empowering People Ethically with the leading open source alternative to Google Analytics that gives you full control over your data. Matomo lets you easily collect data from websites & apps and visualise this data and extract insights. Privacy is built-in. Liberating Web Analytics. Star us on Github? +1. And we love Pull Requests!
https://matomo.org/
GNU General Public License v3.0
19.39k stars 2.6k forks source link

[Bug] page title delay #22305

Open bluetch opened 1 month ago

bluetch commented 1 month ago

What happened?

React website using Matomo, but page title always delay for last page

What should happen?

I expect to track correct and latest page title in Matomo by React. or is there any standard react sample for Matomo?

How can this be reproduced?

`import React, { useEffect } from "react"; import { API_STATUS, useAPI, useAuth } from "@/hooks"; import { ROLE_TYPE } from "@/constants"; import { IAboutData } from "@/pages/about"; import { Helmet } from 'react-helmet';

export const Matomo: React.FC = () => { const { config, meData } = useAuth();

/--- API calls ---/ const { data: sageData, fetchFunc: fetchSageData, status: sageStatus } = useAPI("/settings/sage", []);

useEffect(() => { if (!config || Object.keys(config).length === 0 || !meData) { return; }

if (!sageData) {
  fetchSageData();
}

// eslint-disable-next-line react-hooks/exhaustive-deps

}, [config, meData, sageData, fetchSageData]);

useEffect(() => { if (!config || Object.keys(config).length === 0 || !meData || sageStatus !== API_STATUS.SUCCESS || !sageData) { return; } const title = Helmet.peek()?.title;

const accountAbbr = meData?.type === 2 ? 'L' : 'S';
const roleAbbr = ROLE_TYPE[meData?.role]?.NAME[0].toUpperCase();
const feedbackUserId = `${accountAbbr}_${roleAbbr}_${meData.userId}`;

const _mtm: any[] = (window as any)._mtm || [];
_mtm.push({ 'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start' });
_mtm.push({ 'version': sageData.version });
_mtm.push({ 'sn': sageData.serialNumber });
_mtm.push({ 'feedbackUserId': feedbackUserId });
_mtm.push({ "setDocumentTitle": title });

// Attach _mtm array to the window object
(window as any)._mtm = _mtm;

const d = document,
  g = d.createElement('script'),
  s = d.getElementsByTagName('script')[0];
g.async = true;
g.src = config?.FEEDBACK_URL;
if (s.parentNode) s.parentNode.insertBefore(g, s);

// eslint-disable-next-line react-hooks/exhaustive-deps

}, [config, meData, sageData, sageStatus, Helmet]);

return null; } `

Matomo version

5.1.0

PHP version

No response

Server operating system

No response

What browsers are you seeing the problem on?

Chrome

Computer operating system

No response

Relevant log output

No response

Validations

peterbo commented 1 month ago

In most cases, this is a race condition. The state change needs a bit longer than the title being read for the dataLayer (_mtm). Make sure that the page state has been fully applied before triggering the datalayer push.