Make useAuth resilient when AuthProvider is missing (fallback)
cgen-4d84a008018249a9b15d223d104ac336
This commit is contained in:
parent
ed545e545c
commit
d79788aa57
1 changed files with 33 additions and 1 deletions
|
|
@ -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;
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in a new issue