I´ve set up a google analytics account and and created a new property. Took the tracking id out and then added with react-ga4 like this.
For example on my Album ItemPage
const ItemPage = () => {
const {user} = useContext(AuthContext);
let { item } = useParams();
const [album, setAlbum] = useState({});
useEffect(() => {
const getAlbum = async () => {
try {
const res = await axios.get("/albums/find/" + item, {
});
setAlbum(res.data);
} catch (err) {
console.log(err);
}
};
getAlbum();
}, []);
let location = useLocation();
ReactGA.initialize("G-XXXXXXXXX");
ReactGA.send({hitType: "pageview", page: location.pathname})
return (
<>
<div className={"itemPage"} style={{background: "linear-gradient(to bottom," + color + " -130%,black 90%), url(https://preview.redd.it/o0aq46bb2w111.jpg?width=640&crop=smart&auto=webp&s=6a9216cd0c400677ad95dc66d7cc10e0854aa980)"}}>
<Navbar/>
<Cover/>
<Footer style={{marginTop: "10%"}}/>
</div>
</>
);
}
export default ItemPage;
it sends the correct path and album title to google analytics but ONE click sends SEVEN views. Is there a way to let it max out at 1 time?
You need to move the ReactGA code into your useEffect block so that it only runs once when the page is loaded:
const ItemPage = () => {
const { user } = useContext(AuthContext);
let { item } = useParams();
const [album, setAlbum] = useState({});
useEffect(() => {
const getAlbum = async () => {
try {
const res = await axios.get("/albums/find/" + item, {});
setAlbum(res.data);
} catch (err) {
console.log(err);
}
};
getAlbum();
let location = useLocation();
ReactGA.initialize("G-XXXXXXXXX");
ReactGA.send({ hitType: "pageview", page: location.pathname });
}, []);
return (
<>
<div
className={"itemPage"}
style={{
background:
"linear-gradient(to bottom," +
color +
" -130%,black 90%), url(https://preview.redd.it/o0aq46bb2w111.jpg?width=640&crop=smart&auto=webp&s=6a9216cd0c400677ad95dc66d7cc10e0854aa980)",
}}
>
<Navbar />
<Cover />
<Footer style={{ marginTop: "10%" }} />
</div>
</>
);
};