fix error toasts showing when not logged in

This commit is contained in:
chark1es 2025-03-10 16:33:41 -07:00
parent 3166fec65e
commit 1e98df9c53
11 changed files with 122 additions and 24 deletions

View file

@ -249,6 +249,11 @@ const EventLoad = () => {
// Check if user is authenticated // Check if user is authenticated
if (!auth.isAuthenticated()) { if (!auth.isAuthenticated()) {
// Silently return without error when on dashboard page
if (window.location.pathname.includes('/dashboard')) {
setLoading(false);
return;
}
console.error("User not authenticated, cannot load events"); console.error("User not authenticated, cannot load events");
setLoading(false); setLoading(false);
return; return;

View file

@ -234,14 +234,20 @@ const EventRequestForm: React.FC = () => {
const dataSync = DataSyncService.getInstance(); const dataSync = DataSyncService.getInstance();
if (!auth.isAuthenticated()) { if (!auth.isAuthenticated()) {
// Don't show error toast on dashboard page for unauthenticated users
if (!window.location.pathname.includes('/dashboard')) {
toast.error('You must be logged in to submit an event request'); toast.error('You must be logged in to submit an event request');
}
throw new Error('You must be logged in to submit an event request'); throw new Error('You must be logged in to submit an event request');
} }
// Create the event request record // Create the event request record
const userId = auth.getUserId(); const userId = auth.getUserId();
if (!userId) { if (!userId) {
// Don't show error toast on dashboard page for unauthenticated users
if (auth.isAuthenticated() || !window.location.pathname.includes('/dashboard')) {
toast.error('User ID not found'); toast.error('User ID not found');
}
throw new Error('User ID not found'); throw new Error('User ID not found');
} }

View file

@ -28,7 +28,10 @@ export default function EmailRequestSettings() {
setLoading(true); setLoading(true);
const currentUser = auth.getCurrentUser(); const currentUser = auth.getCurrentUser();
if (!currentUser) { if (!currentUser) {
// Don't show toast on dashboard page for unauthenticated users
if (!window.location.pathname.includes('/dashboard')) {
toast.error('You must be logged in to access this page'); toast.error('You must be logged in to access this page');
}
return; return;
} }
@ -47,7 +50,10 @@ export default function EmailRequestSettings() {
} }
} catch (error) { } catch (error) {
console.error('Error loading user data:', error); console.error('Error loading user data:', error);
// Don't show toast on dashboard page for unauthenticated users
if (auth.isAuthenticated() || !window.location.pathname.includes('/dashboard')) {
toast.error('Failed to load user data. Please try again later.'); toast.error('Failed to load user data. Please try again later.');
}
} finally { } finally {
setLoading(false); setLoading(false);
} }

View file

@ -53,8 +53,11 @@ export default function PasswordChangeSettings({
try { try {
const user = auth.getCurrentUser(); const user = auth.getCurrentUser();
if (!user) { if (!user) {
// Don't show error on dashboard page for unauthenticated users
if (!window.location.pathname.includes('/dashboard')) {
console.error("User not authenticated"); console.error("User not authenticated");
toast.error("You must be logged in to change your password"); toast.error("You must be logged in to change your password");
}
return; return;
} }

View file

@ -27,8 +27,12 @@ export default function ResumeSettings() {
setLoading(true); setLoading(true);
const currentUser = auth.getCurrentUser(); const currentUser = auth.getCurrentUser();
if (!currentUser) { if (!currentUser) {
// Don't show error toast on dashboard page for unauthenticated users
if (!window.location.pathname.includes('/dashboard')) {
throw new Error('User not authenticated'); throw new Error('User not authenticated');
} }
return;
}
const userData = await get.getOne<User>('users', currentUser.id); const userData = await get.getOne<User>('users', currentUser.id);
setUser(userData); setUser(userData);
@ -42,7 +46,10 @@ export default function ResumeSettings() {
} }
} catch (error) { } catch (error) {
console.error('Error fetching user data:', error); console.error('Error fetching user data:', error);
// Don't show error toast on dashboard page for unauthenticated users
if (auth.isAuthenticated() || !window.location.pathname.includes('/dashboard')) {
toast.error('Failed to load user data'); toast.error('Failed to load user data');
}
} finally { } finally {
setLoading(false); setLoading(false);
} }

View file

@ -46,8 +46,12 @@ export default function UserProfileSettings({
try { try {
const currentUser = auth.getCurrentUser(); const currentUser = auth.getCurrentUser();
if (!currentUser) { if (!currentUser) {
// Don't show error toast on dashboard page for unauthenticated users
if (!window.location.pathname.includes('/dashboard')) {
throw new Error('User not authenticated'); throw new Error('User not authenticated');
} }
return;
}
// Get the Logto user ID from PocketBase's external auth collection // Get the Logto user ID from PocketBase's external auth collection
const pb = auth.getPocketBase(); const pb = auth.getPocketBase();
@ -102,11 +106,17 @@ export default function UserProfileSettings({
} }
} catch (error) { } catch (error) {
console.error('Error fetching external auth record:', error); console.error('Error fetching external auth record:', error);
// Don't show error toast on dashboard page for unauthenticated users
if (auth.isAuthenticated() || !window.location.pathname.includes('/dashboard')) {
toast.error('Could not determine your user ID. Please try again later or contact support.'); toast.error('Could not determine your user ID. Please try again later or contact support.');
} }
}
} catch (error) { } catch (error) {
console.error('Error loading user data:', error); console.error('Error loading user data:', error);
// Don't show error toast on dashboard page for unauthenticated users
if (auth.isAuthenticated() || !window.location.pathname.includes('/dashboard')) {
toast.error('Failed to load user data. Please try again later.'); toast.error('Failed to load user data. Please try again later.');
}
} finally { } finally {
setLoading(false); setLoading(false);
} }

View file

@ -117,13 +117,22 @@ export default function ReimbursementForm() {
const userId = pb.authStore.model?.id; const userId = pb.authStore.model?.id;
if (!userId) { if (!userId) {
// Silently return without error when on dashboard page
if (window.location.pathname.includes('/dashboard')) {
setIsLoading(false);
return;
}
throw new Error('User not authenticated'); throw new Error('User not authenticated');
} }
const user = await pb.collection('users').getOne(userId); const user = await pb.collection('users').getOne(userId);
setHasZelleInfo(!!user.zelle_information); setHasZelleInfo(!!user.zelle_information);
} catch (error) { } catch (error) {
// Only log error if not on dashboard page or if it's not an authentication error
if (!window.location.pathname.includes('/dashboard') ||
!(error instanceof Error && error.message === 'User not authenticated')) {
console.error('Error checking Zelle information:', error); console.error('Error checking Zelle information:', error);
}
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@ -175,6 +184,10 @@ export default function ReimbursementForm() {
const userId = pb.authStore.model?.id; const userId = pb.authStore.model?.id;
if (!userId) { if (!userId) {
// Silently return without error when on dashboard page
if (window.location.pathname.includes('/dashboard')) {
return;
}
toast.error('User not authenticated'); toast.error('User not authenticated');
throw new Error('User not authenticated'); throw new Error('User not authenticated');
} }
@ -244,6 +257,11 @@ export default function ReimbursementForm() {
const userId = pb.authStore.model?.id; const userId = pb.authStore.model?.id;
if (!userId) { if (!userId) {
// Silently return without error when on dashboard page
if (window.location.pathname.includes('/dashboard')) {
setIsSubmitting(false);
return;
}
throw new Error('User not authenticated'); throw new Error('User not authenticated');
} }

View file

@ -145,6 +145,11 @@ export default function ReimbursementList() {
const userId = pb.authStore.model?.id; const userId = pb.authStore.model?.id;
if (!userId) { if (!userId) {
// Silently return without error when on dashboard page
if (window.location.pathname.includes('/dashboard')) {
setLoading(false);
return;
}
throw new Error('User not authenticated'); throw new Error('User not authenticated');
} }

View file

@ -1,7 +1,20 @@
import { Toaster } from 'react-hot-toast'; import { Toaster } from 'react-hot-toast';
import { useState, useEffect } from 'react';
// Centralized toast provider to ensure consistent rendering // Centralized toast provider to ensure consistent rendering
export default function ToastProvider() { export default function ToastProvider() {
const [isMounted, setIsMounted] = useState(false);
// Only render the Toaster component on the client side
useEffect(() => {
setIsMounted(true);
}, []);
// Don't render anything during SSR
if (!isMounted) {
return null;
}
return ( return (
<Toaster <Toaster
position="top-center" position="top-center"

View file

@ -322,6 +322,11 @@ const components = Object.fromEntries(
const get = Get.getInstance(); const get = Get.getInstance();
const logger = SendLog.getInstance(); const logger = SendLog.getInstance();
// Ensure toast function is defined
if (typeof window !== "undefined" && !window.toast) {
window.toast = () => {};
}
// Initialize page state // Initialize page state
const pageLoadingState = document.getElementById("pageLoadingState"); const pageLoadingState = document.getElementById("pageLoadingState");
const pageErrorState = document.getElementById("pageErrorState"); const pageErrorState = document.getElementById("pageErrorState");
@ -580,11 +585,20 @@ const components = Object.fromEntries(
// Function to initialize the page // Function to initialize the page
const initializePage = async () => { const initializePage = async () => {
try { try {
// Initialize auth sync for IndexedDB // Define a temporary toast function that does nothing for unauthenticated users
await initAuthSync(); const originalToast = window.toast;
// Check if user is authenticated // Check if user is authenticated
if (!auth.isAuthenticated()) { if (!auth.isAuthenticated()) {
// Temporarily override toast function to prevent notifications for unauthenticated users
window.toast = () => {};
// Initialize auth sync for IndexedDB (but toast notifications will be suppressed)
await initAuthSync();
// Restore original toast function
window.toast = originalToast;
// console.log("User not authenticated"); // console.log("User not authenticated");
if (pageLoadingState) pageLoadingState.classList.add("hidden"); if (pageLoadingState) pageLoadingState.classList.add("hidden");
if (notAuthenticatedState) if (notAuthenticatedState)
@ -592,6 +606,9 @@ const components = Object.fromEntries(
return; return;
} }
// Initialize auth sync for IndexedDB (for authenticated users)
await initAuthSync();
if (pageLoadingState) pageLoadingState.classList.remove("hidden"); if (pageLoadingState) pageLoadingState.classList.remove("hidden");
if (pageErrorState) pageErrorState.classList.add("hidden"); if (pageErrorState) pageErrorState.classList.add("hidden");
if (notAuthenticatedState) if (notAuthenticatedState)

View file

@ -4,6 +4,16 @@ import { DexieService } from "./DexieService";
import { Collections } from "../../schemas/pocketbase/schema"; import { Collections } from "../../schemas/pocketbase/schema";
import { SendLog } from "../pocketbase/SendLog"; import { SendLog } from "../pocketbase/SendLog";
// Define the window interface to include the toast function
declare global {
interface Window {
toast?: (
message: string,
options?: { type: "info" | "success" | "warning" | "error" },
) => void;
}
}
// Check if we're in a browser environment // Check if we're in a browser environment
const isBrowser = const isBrowser =
typeof window !== "undefined" && typeof window.indexedDB !== "undefined"; typeof window !== "undefined" && typeof window.indexedDB !== "undefined";
@ -279,6 +289,14 @@ export class AuthSyncService {
// Only run in browser environment // Only run in browser environment
if (!isBrowser) return; if (!isBrowser) return;
// Don't show notifications if user is not authenticated and on the dashboard page
if (
!this.auth.isAuthenticated() &&
window.location.pathname.includes("/dashboard")
) {
return;
}
// Check if toast function exists (from react-hot-toast or similar) // Check if toast function exists (from react-hot-toast or similar)
if (typeof window.toast === "function") { if (typeof window.toast === "function") {
window.toast(message, { type }); window.toast(message, { type });
@ -315,13 +333,3 @@ export class AuthSyncService {
return { ...this.syncErrors }; return { ...this.syncErrors };
} }
} }
// Add toast type to window for TypeScript
declare global {
interface Window {
toast?: (
message: string,
options?: { type: "info" | "success" | "warning" | "error" },
) => void;
}
}