Skip to content

Commit db83d52

Browse files
committed
リロードエラー問題を解決
1 parent 7b253fb commit db83d52

File tree

1 file changed

+32
-19
lines changed

1 file changed

+32
-19
lines changed

web/firebase/auth/lib.ts

Lines changed: 32 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,24 @@ let user: User;
99
let token: string;
1010

1111
const auth = getAuth(app);
12-
onAuthStateChanged(auth, async (u: User | null) => {
13-
if (u != null) {
14-
user = u;
15-
token = await user.getIdToken();
16-
}
12+
13+
// 認証状態の完了を待機するためのPromiseを作成
14+
const authInitialized = new Promise<void>((resolve) => {
15+
onAuthStateChanged(auth, async (u: User | null) => {
16+
if (u != null) {
17+
user = u;
18+
token = await user.getIdToken();
19+
}
20+
resolve();
21+
});
1722
});
1823

1924
async function refreshToken() {
2025
token = await user.getIdToken(true);
2126
}
2227

2328
export async function getIdToken(): Promise<IDToken> {
29+
await authInitialized;
2430
if (token) return token;
2531
await refreshToken();
2632
return token;
@@ -39,20 +45,27 @@ export async function credFetch(
3945
path: string,
4046
body?: unknown,
4147
): Promise<Response> {
42-
const idToken = await getIdToken();
43-
const init: RequestInit = { method };
44-
if (body) {
45-
init.body = JSON.stringify(body);
46-
init.headers = {
47-
"Content-Type": "application/json",
48-
};
49-
}
48+
try {
49+
const idToken = await getIdToken();
50+
const init: RequestInit = { method };
51+
if (body) {
52+
init.body = JSON.stringify(body);
53+
init.headers = {
54+
"Content-Type": "application/json",
55+
};
56+
}
5057

51-
let res = await fetch(`${path}?token=${idToken}`, init);
52-
if (res.status === 401) {
53-
await refreshToken();
54-
res = await fetch(`${path}?token=${idToken}`);
55-
}
58+
let res: Response;
59+
res = await fetch(`${path}?token=${idToken}`, init);
60+
61+
if (res.status === 401) {
62+
await refreshToken();
63+
res = await fetch(`${path}?token=${idToken}`, init);
64+
}
5665

57-
return res;
66+
return res;
67+
} catch (error) {
68+
console.error("Error in credFetch function:", error);
69+
throw error;
70+
}
5871
}

0 commit comments

Comments
 (0)