Spaces:
Build error
Build error
fix(lint): lazy-init loading state to avoid setLoading(false) inside effect body
Browse filesInstead of calling setLoading(false) synchronously in the useEffect early-return
branch (which triggers the react-hooks/set-state-in-effect error), initialize
loading lazily: it's true only when a token exists and needs server validation.
With no token, loading starts as false and the effect returns early with no setState.
frontend/src/lib/auth.tsx
CHANGED
|
@@ -28,14 +28,17 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
| 28 |
const [token, setToken] = useState<string | null>(
|
| 29 |
() => (typeof window !== "undefined" ? localStorage.getItem("token") : null)
|
| 30 |
);
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
// ββ Validate saved token on mount βββββββββββββββββ
|
|
|
|
|
|
|
| 34 |
useEffect(() => {
|
| 35 |
-
if (!token)
|
| 36 |
-
setLoading(false);
|
| 37 |
-
return;
|
| 38 |
-
}
|
| 39 |
api
|
| 40 |
.get<User>("/api/v1/auth/me", { token })
|
| 41 |
.then(setUser)
|
|
|
|
| 28 |
const [token, setToken] = useState<string | null>(
|
| 29 |
() => (typeof window !== "undefined" ? localStorage.getItem("token") : null)
|
| 30 |
);
|
| 31 |
+
// loading=true only when a token exists and needs server validation.
|
| 32 |
+
// If there's no token we're already done β no effect setState needed.
|
| 33 |
+
const [loading, setLoading] = useState<boolean>(
|
| 34 |
+
() => typeof window !== "undefined" && !!localStorage.getItem("token")
|
| 35 |
+
);
|
| 36 |
|
| 37 |
// ββ Validate saved token on mount βββββββββββββββββ
|
| 38 |
+
// NOTE: no synchronous setState here β setLoading/setUser/setToken are
|
| 39 |
+
// only called inside async callbacks (.then / .catch / .finally).
|
| 40 |
useEffect(() => {
|
| 41 |
+
if (!token) return; // loading is already false when token is null
|
|
|
|
|
|
|
|
|
|
| 42 |
api
|
| 43 |
.get<User>("/api/v1/auth/me", { token })
|
| 44 |
.then(setUser)
|