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