convex
Version:
Client for the Convex Cloud
64 lines (63 loc) • 2.03 kB
JavaScript
import React, {
createContext,
useContext,
useEffect,
useState
} from "react";
import { ConvexProvider } from "./client.js";
const ConvexAuthContext = createContext(void 0);
export function useConvexAuth() {
const authContext = useContext(ConvexAuthContext);
if (authContext === void 0) {
throw new Error(
"Could not find `ConvexProviderWithAuth` (or `ConvexProviderWithClerk` or `ConvexProviderWithAuth0`) as an ancestor component. This component may be missing, or you might have two instances of the `convex/react` module loaded in your project."
);
}
return authContext;
}
export function ConvexProviderWithAuth({
children,
client,
useAuth
}) {
const { isLoading, isAuthenticated, fetchAccessToken } = useAuth();
const [isConvexAuthenticated, setIsConvexAuthenticated] = useState(null);
useEffect(() => {
let isThisEffectRelevant = true;
async function setToken() {
client.setAuth(fetchAccessToken, (isAuthenticated2) => {
if (isThisEffectRelevant) {
setIsConvexAuthenticated(isAuthenticated2);
}
});
}
if (isAuthenticated) {
void setToken();
return () => {
isThisEffectRelevant = false;
setIsConvexAuthenticated(
(isConvexAuthenticated2) => isConvexAuthenticated2 ? false : null
);
client.clearAuth();
};
}
}, [isAuthenticated, fetchAccessToken, isLoading, client]);
if (isLoading && isConvexAuthenticated !== null) {
setIsConvexAuthenticated(null);
}
if (!isLoading && !isAuthenticated && isConvexAuthenticated !== false) {
setIsConvexAuthenticated(false);
}
return /* @__PURE__ */ React.createElement(
ConvexAuthContext.Provider,
{
value: {
isLoading: isConvexAuthenticated === null,
isAuthenticated: isAuthenticated && (isConvexAuthenticated ?? false)
}
},
/* @__PURE__ */ React.createElement(ConvexProvider, { client }, children)
);
}
//# sourceMappingURL=ConvexAuthState.js.map
;