Skip to content

Commit

Permalink
Merge pull request #317 from Aar-if/cachingLatest
Browse files Browse the repository at this point in the history
Issue #PS-919 feat: [FRONTEND] Implementation of caching
  • Loading branch information
itsvick authored Jun 26, 2024
2 parents da5163b + 46c6214 commit a5e7cfd
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 47 deletions.
25 changes: 25 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@mui/material": "^5.15.15",
"@project-sunbird/client-services": "^7.0.6",
"@project-sunbird/telemetry-sdk": "^1.3.0",
"@tanstack/react-query": "^5.45.1",
"axios": "^1.6.8",
"date-fns": "^3.6.0",
"fingerprintjs2": "^2.1.4",
Expand Down
5 changes: 5 additions & 0 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ import { initGA, logPageView } from '../utils/googleAnalytics';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import Head from 'next/head';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';


const queryClient = new QueryClient();
const ColorModeContext = React.createContext({ toggleColorMode: () => {} });
const poppins = Poppins({
weight: ['100', '200', '300', '400', '500', '600', '700', '800', '900'],
Expand Down Expand Up @@ -127,7 +130,9 @@ function App({ Component, pageProps }: AppProps) {
<CssVarsProvider theme={customTheme}>
{/* <ModeToggle /> */}
<Container maxWidth="md" style={{ padding: 0 }}>
<QueryClientProvider client={queryClient}>
<Component {...pageProps} />
</QueryClientProvider>
<ToastContainer
position="bottom-left"
autoClose={3000}
Expand Down
31 changes: 12 additions & 19 deletions src/pages/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import useDeterminePathColor from '../hooks/useDeterminePathColor';
import { useRouter } from 'next/navigation';
import { useTheme } from '@mui/material/styles';
import { useTranslation } from 'next-i18next';

import { useCohortList } from '@/services/queries';
interface DashboardProps {
// buttonText: string;
}
Expand Down Expand Up @@ -95,6 +95,7 @@ const Dashboard: React.FC<DashboardProps> = () => {
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(currentDate.getDate() - modifyAttendanceLimit);
const formattedSevenDaysAgo = shortDateFormat(sevenDaysAgo);
const [userId, setUserId] = React.useState<string | null>(null);

useEffect(() => {
setIsClient(true);
Expand Down Expand Up @@ -128,29 +129,28 @@ const Dashboard: React.FC<DashboardProps> = () => {
useEffect(() => {
if (typeof window !== 'undefined' && window.localStorage) {
const token = localStorage.getItem('token');
const storedUserId = localStorage.getItem('userId');
setClassId(localStorage.getItem('classId') || '');
if (token) {
setIsAuthenticated(true);
} else {
router.push('/login');
}
setUserId(storedUserId);
}
}, []);

// API call to get center list
useEffect(() => {
const fetchCohortList = async () => {
const userId = localStorage.getItem('userId');
setLoading(true);
try {
if (userId) {

const limit = 0;
const page = 0;
const filters = { userId: userId };
const resp = await cohortList({ limit, page, filters });
const { data, error, isLoading } = useCohortList(limit, page, filters);
// API call to get center list
useEffect(() => {
if (data) {

const extractedNames = resp?.results?.cohortDetails;
localStorage.setItem('parentCohortId', extractedNames?.[0].parentId);
const extractedNames = data?.results?.cohortDetails;
localStorage.setItem('parentCohortId', extractedNames?.[0].cohortData?.parentId);

const filteredData = extractedNames
?.map((item: any) => ({
Expand All @@ -176,14 +176,7 @@ const Dashboard: React.FC<DashboardProps> = () => {
}
setLoading(false);
}
} catch (error) {
console.error('Error fetching cohort list:', error);
showToastMessage(t('COMMON.SOMETHING_WENT_WRONG'), 'error');
setLoading(false);
}
};
fetchCohortList();
}, []);
}, [data]);

//API for getting student list
useEffect(() => {
Expand Down
50 changes: 22 additions & 28 deletions src/pages/profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import { useRouter } from 'next/router';
import { useTranslation } from 'next-i18next';
import userPicture from '@/assets/images/imageOne.jpg';
import user_placeholder from '../assets/images/user_placeholder.png';
import { useProfileInfo } from '@/services/queries';

interface FieldOption {
name: string;
Expand Down Expand Up @@ -108,6 +109,7 @@ const TeacherProfile = () => {
const [hasInputChanged, setHasInputChanged] = React.useState<boolean>(false);
const [isValidationTriggered, setIsValidationTriggered] =
React.useState<boolean>(false);
const [userId, setUserId] = useState<string | null>(null);

const handleNameFieldChange = (event: ChangeEvent<HTMLInputElement>) => {
const { value } = event.target;
Expand All @@ -131,12 +133,15 @@ const TeacherProfile = () => {
useEffect(() => {
if (typeof window !== 'undefined' && window.localStorage) {
const token = localStorage.getItem('token');
const storedUserId = localStorage.getItem('userId');
if (token) {
setIsAuthenticated(true);
} else {
router.push('/login');
}
setUserId(storedUserId);
}

}, []);

// find Address
Expand All @@ -145,20 +150,21 @@ const TeacherProfile = () => {
return field ? field.value[0] : null;
};

const fetchUserDetails = async () => {
setLoading(true);
if (typeof window !== 'undefined' && window.localStorage) {
const userId = localStorage.getItem('userId');
const { data, error, isLoading } = useProfileInfo(userId ?? '', true);

try {
if (userId) {
const response = await getUserDetails(userId, true);
console.log('response', response);
useEffect(() => {
setLoading(isLoading);

const data = response?.result;
if (error) {
setIsError(true);
showToastMessage(t('COMMON.SOMETHING_WENT_WRONG'), 'error');
console.error('Error fetching user details:', error);
} else {
setIsError(false);
}

if (data) {
const userData = data?.userData;
const userData = data?.result?.userData;
setUserData(userData);
setUserName(userData?.name);
const customDataFields = userData?.customFields;
Expand All @@ -170,27 +176,15 @@ const TeacherProfile = () => {
setUnitName(unitName);
const blockName = getFieldValue(customDataFields, 'Block Name');
setBlockName(blockName);
setLoading(false);

}
} else {
setLoading(false);

setIsData(false);
console.log('No data Found');
}
}
setIsError(false);
} catch (error) {
setLoading(false);
setIsError(true);
showToastMessage(t('COMMON.SOMETHING_WENT_WRONG'), 'error');
console.error('Error fetching user details:', error);
}
}
};

useEffect(() => {
fetchUserDetails();
}, []);

}, [data, error, isLoading]);

const handleClickImage = () => {
fileInputRef.current && fileInputRef.current.click();
Expand Down Expand Up @@ -454,7 +448,7 @@ const TeacherProfile = () => {
handleClose();

console.log(response.params.successmessage);
fetchUserDetails();

setIsError(false);
setLoading(false);
}
Expand Down Expand Up @@ -1142,7 +1136,7 @@ const TeacherProfile = () => {
) : (
<Box mt={5}>
<Typography textAlign={'center'}>
{t('COMMON.SOMETHING_WENT_WRONG')}
{t('COMMON.LOADING')}
</Typography>
</Box>
)}{' '}
Expand Down
24 changes: 24 additions & 0 deletions src/services/queries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useQuery } from "@tanstack/react-query";
import { getUserDetails } from "./ProfileService";
import { cohortList } from "./CohortServices";
import { refetchInterval, gcTime } from "@/utils/app.constant";

export function useProfileInfo(userId: string | string[], fieldValue: boolean) {
return useQuery({

queryKey: ['profile', userId],
queryFn: () => getUserDetails(userId, fieldValue),
refetchInterval: refetchInterval,
gcTime: gcTime
});
}

export function useCohortList( limit: any, page: any, filters: any) {
return useQuery({
queryKey: ['cohort'],
queryFn: () => cohortList({limit , page, filters}),
refetchInterval: refetchInterval,
gcTime: gcTime
});
}

2 changes: 2 additions & 0 deletions src/utils/app.constant.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export const limit: number = 300;
export const refetchInterval: number = 5 * 60 * 1000;
export const gcTime: number = 10 * 60 * 1000;

0 comments on commit a5e7cfd

Please sign in to comment.