Update
This commit is contained in:
27
resources/js/plugins/GA4Context.jsx
Normal file
27
resources/js/plugins/GA4Context.jsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import { createContext, useContext, useEffect } from 'react';
|
||||
import ReactGA from 'react-ga4';
|
||||
|
||||
const GA4Context = createContext();
|
||||
|
||||
export const useGA4 = () => {
|
||||
const context = useContext(GA4Context);
|
||||
if (context === undefined) {
|
||||
throw new Error('useGA4 must be used within a GA4Provider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const GA4Provider = ({ children }) => {
|
||||
useEffect(() => {
|
||||
const GOOGLE_TAG_ID = import.meta.env.VITE_GOOGLE_TAG_ID;
|
||||
|
||||
if (GOOGLE_TAG_ID) {
|
||||
ReactGA.initialize(GOOGLE_TAG_ID);
|
||||
console.log('Google Analytics 4 initialized with ID:', GOOGLE_TAG_ID);
|
||||
} else {
|
||||
console.warn('GA4 is not set. Google Analytics 4 will not be initialized.');
|
||||
}
|
||||
}, []);
|
||||
|
||||
return <GA4Context.Provider value={ReactGA}>{children}</GA4Context.Provider>;
|
||||
};
|
||||
Reference in New Issue
Block a user