-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTryRefresh.tsx
46 lines (41 loc) · 1.28 KB
/
TryRefresh.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import SuperTokens from "supertokens-auth-react";
import Session from "supertokens-auth-react/recipe/session";
/**
* A component that will refresh the user's session if their current session has expired.
*/
export const TryRefresh = () => {
const router = useRouter();
const [didError, setDidError] = useState(false);
useEffect(() => {
/**
* `attemptRefreshingSession` will call the refresh token endpoint to try and
* refresh the session. This will throw an error if the session cannot be refreshed.
*/
void Session.attemptRefreshingSession()
.then((hasSession) => {
/**
* If the user has a valid session, we reload the page to restart the flow
* with valid session tokens
*/
if (hasSession) {
router.refresh();
} else {
SuperTokens.redirectToAuth();
}
})
.catch(() => {
setDidError(true);
});
}, [router]);
/**
* We add this check to make sure we handle the case where the refresh API fails with
* an unexpected error
*/
if (didError) {
return <div>Something went wrong, please reload the page</div>;
}
return <div>Loading...</div>;
};