43 lines
1.1 KiB
JavaScript
43 lines
1.1 KiB
JavaScript
import {useState,useEffect} from "react";
|
|
import AuthRepository from "../repositories/AuthRepository";
|
|
import {cacheProfileData, getCachedProfileData} from "../slices/apiDataManager";
|
|
import {useSelector} from "react-redux";
|
|
|
|
let hasFetched = false;
|
|
|
|
export const useProfile = () => {
|
|
const loggedUser = useSelector( ( store ) => store.globalVariables.loginUser );
|
|
const [profile, setProfile] = useState(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState("");
|
|
|
|
const fetchData = async () => {
|
|
try {
|
|
setLoading(true);
|
|
let response = await AuthRepository.profile();
|
|
setProfile(response.data);
|
|
cacheProfileData(response.data);
|
|
} catch (error) {
|
|
setError("Failed to fetch data.");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (!hasFetched) {
|
|
hasFetched = true;
|
|
if (!loggedUser) {
|
|
fetchData();
|
|
} else {
|
|
setProfile(loggedUser);
|
|
}
|
|
}
|
|
|
|
setProfile(loggedUser);
|
|
|
|
}, [loggedUser]);
|
|
|
|
return { profile, loading, error };
|
|
};
|