TanStackT
TanStack7mo ago
4 replies
military-pink

useMutation in Context+Provider infinite calls

Hi all, thanks in advance for your time.

I'm using react-router & tanstack query.

I need a POST to get fired off upon App initialisation and I figured I could do that using a createContext and provider to then be able to access it a bit deeper down easily, that'd be useful. I am completely unable to get this to work or understand why I am getting infinite re-renders. I have tried everything chat gippity is suggesting and have googled as much as possible.

In AuthContext.tsx:
import { useMutation } from "@tanstack/react-query";
import { getFingerprint } from "@thumbmarkjs/thumbmarkjs";
import { createContext, useState, type ReactNode } from "react";

type TAuthContext = {
  hasSession: boolean;
};

const AuthContext = createContext<TAuthContext | undefined>(undefined);

type TAuthProviderProps = {
  children: ReactNode;
};

function AuthProvider({ children }: TAuthProviderProps) {
  const [hasSession, setHasSession] = useState<boolean>(false);
  const mutation = useMutation({
    mutationFn: async () => {
      const fingerprint = await getFingerprint();
      const response = await fetch(
        "http://localhost:8000/api/v1/auth/session/",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          credentials: "include",
          body: JSON.stringify({
            fingerprint: fingerprint,
          }),
        }
      );
      if (!response.ok) {
        throw new Error();
      } else {
        return await response.json();
      }
    },
    onSuccess: () => {
      setHasSession(true);
    },
    onError: () => {
      console.log("Error!");
    },
  });

  if (!hasSession) {
    // mutation.mutate(); BOOM, infinite calls
    // setHasSession(true) KIND of works here, but it behaves weirdly in NotFound routes ("*")
  }

  return (
    <AuthContext.Provider value={{ hasSession }}>
      {children}
    </AuthContext.Provider>
  );
}

export { AuthProvider, AuthContext };
Was this page helpful?