Make useAuth resilient when AuthProvider is missing (fallback)

cgen-4d84a008018249a9b15d223d104ac336
This commit is contained in:
Builder.io 2025-09-30 04:15:05 +00:00
parent ed545e545c
commit d79788aa57

View file

@ -30,11 +30,43 @@ interface AuthContextType {
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
let warnedMissingProvider = false;
const missingProviderFallback: AuthContextType = {
user: null,
profile: null,
roles: [],
session: null,
loading: true,
profileComplete: false,
signIn: async () => {
throw new Error("AuthProvider is not mounted. Please ensure your app is wrapped with <AuthProvider>.");
},
signUp: async () => {
throw new Error("AuthProvider is not mounted. Please ensure your app is wrapped with <AuthProvider>.");
},
signInWithOAuth: async () => {
throw new Error("AuthProvider is not mounted. Please ensure your app is wrapped with <AuthProvider>.");
},
signOut: async () => {
throw new Error("AuthProvider is not mounted. Please ensure your app is wrapped with <AuthProvider>.");
},
updateProfile: async () => {
throw new Error("AuthProvider is not mounted. Please ensure your app is wrapped with <AuthProvider>.");
},
refreshProfile: async () => {
throw new Error("AuthProvider is not mounted. Please ensure your app is wrapped with <AuthProvider>.");
},
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within an AuthProvider");
if (!warnedMissingProvider) {
console.warn("useAuth called without an AuthProvider. Falling back to safe defaults.");
warnedMissingProvider = true;
}
return missingProviderFallback;
}
return context;
};