s22
This commit is contained in:
44
src/lib/isLoggedIn.jsx
Normal file
44
src/lib/isLoggedIn.jsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
const USER_API_URL = 'https://host-api.cs1.hz.siliconpin.com/v1/users/index.php';
|
||||
|
||||
export const useIsLoggedIn = () => {
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(null); // null means "unknown"
|
||||
const [sessionData, setSessionData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkLoginStatus = async () => {
|
||||
try {
|
||||
const response = await fetch(`${USER_API_URL}?query=isLoggedIn`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
const data = await response.json();
|
||||
setIsLoggedIn(!!data?.isLoggedIn);
|
||||
setSessionData(data?.session_data || null);
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
setError(err);
|
||||
setIsLoggedIn(false);
|
||||
setSessionData(null);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkLoginStatus();
|
||||
}, []);
|
||||
|
||||
return { isLoggedIn, sessionData, loading, error };
|
||||
};
|
||||
|
||||
const IsLoggedIn = ({ children, fallback = null }) => {
|
||||
const { isLoggedIn, loading, error } = useIsLoggedIn();
|
||||
|
||||
if (loading) return <div>Loading...</div>;
|
||||
if (error) return <div>Error checking login status</div>;
|
||||
|
||||
return isLoggedIn ? children : fallback;
|
||||
};
|
||||
|
||||
export default IsLoggedIn;
|
||||
Reference in New Issue
Block a user