@@ -65,35 +65,50 @@ export const PayloadSessionProvider: React.FC<Props<CollectionSlug>> = <
65
65
/**
66
66
* Function to fetch the session
67
67
*/
68
- const fetchSession = useCallback ( async ( ) => {
69
- // Fetch the session from the server
70
- const response = await fetch ( `/api/${ userCollectionSlug } /me` ) ;
71
- const result : { user : DataFromCollectionSlug < TSlug > ; exp : number } = await response . json ( ) ;
72
-
73
- // Set loading to false
74
- setIsLoading ( false ) ;
75
-
76
- // If the response is not ok or the user is not present, return null
77
- if ( ! response . ok || ! result . user ) {
78
- return null ;
79
- }
80
-
81
- // Update the local session
82
- const localSession = {
83
- user : result . user ,
84
- expires : new Date ( result . exp * 1000 ) . toISOString ( ) ,
85
- } ;
86
- setLocalSession ( localSession ) ;
87
-
88
- // Return the session
89
- return localSession ;
90
- } , [ userCollectionSlug ] ) ;
68
+ const fetchSession = useCallback (
69
+ async ( { signal } : { signal ?: AbortSignal } = { } ) => {
70
+ // Fetch the session from the server
71
+ const response = await fetch ( `/api/${ userCollectionSlug } /me` , {
72
+ signal,
73
+ } ) ;
74
+ const result : { user : DataFromCollectionSlug < TSlug > | null ; exp : number } =
75
+ await response . json ( ) ;
76
+
77
+ // Set loading to false
78
+ setIsLoading ( false ) ;
79
+
80
+ // If the response is not ok or the user is not present, return null
81
+ if ( ! response . ok || ! result . user ) {
82
+ return null ;
83
+ }
84
+
85
+ // Update the local session
86
+ const localSession = {
87
+ user : result . user ,
88
+ expires : new Date ( result . exp * 1000 ) . toISOString ( ) ,
89
+ } ;
90
+ setLocalSession ( localSession ) ;
91
+
92
+ // Return the session
93
+ return localSession ;
94
+ } ,
95
+ [ userCollectionSlug ] ,
96
+ ) ;
91
97
92
98
/**
93
99
* On mount, fetch the session
94
100
*/
95
101
useEffect ( ( ) => {
96
- void fetchSession ( ) ;
102
+ const abortController = new AbortController ( ) ;
103
+
104
+ void fetchSession ( {
105
+ signal : abortController . signal ,
106
+ } ) ;
107
+
108
+ // Abort the fetch on unmount
109
+ return ( ) => {
110
+ abortController . abort ( ) ;
111
+ } ;
97
112
} , [ fetchSession ] ) ;
98
113
99
114
/**
@@ -104,7 +119,8 @@ export const PayloadSessionProvider: React.FC<Props<CollectionSlug>> = <
104
119
const response = await fetch ( `/api/${ userCollectionSlug } /refresh-token` , {
105
120
method : "POST" ,
106
121
} ) ;
107
- const result : { user : DataFromCollectionSlug < TSlug > ; exp : number } = await response . json ( ) ;
122
+ const result : { user : DataFromCollectionSlug < TSlug > | null ; exp : number } =
123
+ await response . json ( ) ;
108
124
109
125
// If the response is not ok or the user is not present, return null
110
126
if ( ! response . ok || ! result . user ) {
0 commit comments