Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

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

Open
kvalium opened this issue Dec 7, 2021 · 2 comments
Open

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

kvalium opened this issue Dec 7, 2021 · 2 comments

Comments

@kvalium
Copy link

kvalium commented Dec 7, 2021

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
Copy link
Contributor

@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
Copy link
Author

kvalium commented Dec 16, 2021

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 ;)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants