JamalJ
Convex Community16mo ago
11 replies
Jamal

Need a little react help

Hello family, its been a while. So for my site I wanted to save a simple count of users visited. I wrote this code:
"use client";

import { useMutation } from "convex/react";
import { useEffect } from "react";
import { api } from "../../convex/_generated/api";
import useLocalStorage from "@/hooks/useLocalStorage";

const GlobalStatsTracker = () => {
  const [viewCounted, setViewCounted] = useLocalStorage<"no" | "yes">(
    "view_counted",
    {
      defaultValue: "no",
    }
  );
  const updateGlobalStats = useMutation(api.global_kv.updateGlobalStats);

  useEffect(() => {
    console.table({
      viewCounted,
      "window.location.host.includes('localhost')":
        window.location.host.includes("localhost"),
      "typeof window === 'undefined'": typeof window === "undefined",
    });

    if (typeof window === "undefined") return;
    if (viewCounted === "yes") return;
    if (process.env.NODE_ENV === "development") return;

    updateGlobalStats({ total_users_visited: true })
      .then(() => {
        setViewCounted("yes");
      })
      .catch(console.error);
  }, [viewCounted]);

  return null;
};

export default GlobalStatsTracker;

which works fine but for some reason every page refresh the updateGlobalStats is called even when the view has been set in local storage? This should not happen

viewCounted    'yes'
window.location.host.includes('localhost')    true
typeof window === 'undefined'    false

This is the console output.
Was this page helpful?