1+ import { queryClient } from './queryClient' ;
2+
3+ /**
4+ * Handle unauthorized errors by updating the auth state in the query cache
5+ * This will trigger the AuthModal to appear
6+ */
7+ export function handleUnauthorized ( ) {
8+ // Set auth state to false to trigger the AuthModal
9+ queryClient . setQueryData ( [ 'auth' ] , false ) ;
10+ }
11+
112// Common error handling for API responses
213export async function handleResponse ( response : Response ) {
3- if ( ! response . ok ) {
4- if ( response . status === 401 ) {
5- throw new Error ( 'Unauthorized' ) ;
6- }
7-
8- const errorText = await response . text ( ) ;
9- throw new Error ( errorText || `API error: ${ response . status } ` ) ;
14+ if ( ! response . ok ) {
15+ if ( response . status === 401 ) {
16+ // Update auth state when 401 is encountered
17+ handleUnauthorized ( ) ;
18+ throw new Error ( 'Unauthorized' ) ;
1019 }
1120
12- // For endpoints that return no content
13- if ( response . status === 204 ) {
14- return null ;
15- }
16-
17- // For endpoints that return JSON
18- return response . json ( ) ;
21+ const errorText = await response . text ( ) ;
22+ throw new Error ( errorText || `API error: ${ response . status } ` ) ;
1923 }
2024
21- // Base fetch function with error handling
22- export async function fetchApi ( url : string , options ?: RequestInit ) {
25+ // For endpoints that return no content
26+ if ( response . status === 204 ) {
27+ return null ;
28+ }
29+
30+ // For endpoints that return JSON
31+ return response . json ( ) ;
32+ }
33+
34+ // Base fetch function with error handling
35+ export async function fetchApi ( url : string , options ?: RequestInit ) {
36+ try {
2337 const response = await fetch ( url , {
2438 ...options ,
2539 credentials : 'include' ,
@@ -30,4 +44,8 @@ export async function handleResponse(response: Response) {
3044 } ) ;
3145
3246 return handleResponse ( response ) ;
33- }
47+ } catch ( error ) {
48+ // Re-throw the error after handling it
49+ throw error ;
50+ }
51+ }
0 commit comments