jonkoops / matomo-tracker

Stand alone library for using matamo tracking in frontend projects
Mozilla Public License 2.0
141 stars 62 forks source link

Refresh or reset React context instance to track logged users #700

Open kvalium opened 2 years ago

kvalium commented 2 years ago

I have a React frontend where users have to log in. The tracking instance is created one the user is logged in with userId corresponding to user's first name and last name.

When user A logs out then user B logs in, Matomo backend still track events for user A

Describe the solution you'd like How to programatically refresh or reset the Matomo Instance / Context?

Additional context This is my Matomo tracker Provider:

export const TrackingWrapper = ({ children }: { children: React.ReactNode }) => {
  const [{ firstName, lastName }] = useContext(UserContext); 

  const trackerInstance = useMemo(
    () =>
      createInstance({
        urlBase: MATOMO_TRACKER_URL,
        userId: `${firstName}  ${lastName}`, // Will change on different user log out / log in
        siteId: 1,
        linkTracking: false,
        configurations: {
          disableCookies: true,
        },
      }),
    [firstName, lastName]
  );

  return <MatomoProvider value={trackerInstance}>{children}</MatomoProvider>;
};
chrisvanmook commented 2 years ago

@kvalium It's best to not use createInstance inside a react component, but outside so it won't create a new instance every time you render the page. Please read this document

In order to track the new user, you can use the useMatomo hook like this inside your component:

const { pushInstruction } = useMatomo();
pushInstruction('setUserId', 'USER_ID_HERE');
kvalium commented 2 years ago

Hello @chrisvanmook, I had to put it on a component because I needed my user context data to build the user id instance, but your solution seems to solve both problems, I'll test it as soon as possible, thanks ;)