1- import { useEffect , useState } from "react" ;
1+ import { useCallback , useEffect , useState } from "react" ;
22import CourseAPIClient from "../APIClients/CourseAPIClient" ;
33import { CourseModule } from "../types/CourseTypes" ;
44
@@ -7,31 +7,46 @@ const useCourseModules = (unitId: string) => {
77 const [ loading , setLoading ] = useState < boolean > ( true ) ;
88 const [ error , setError ] = useState < string | null > ( null ) ;
99
10- useEffect ( ( ) => {
11- if ( ! unitId ) return ; // Prevent API call if unitId is empty
10+ const [ moduleDataCache , setModuleDataCache ] = useState <
11+ Record < string , CourseModule [ ] >
12+ > ( { } ) ;
13+
14+ const fetchCourseModules = useCallback ( async ( ) => {
15+ try {
16+ console . log ( moduleDataCache ) ;
17+ if ( moduleDataCache [ unitId ] ) {
18+ setCourseModules ( moduleDataCache [ unitId ] ) ;
19+ return ;
20+ }
1221
13- const fetchCourseModules = async ( ) => {
14- try {
15- setLoading ( true ) ;
16- setError ( null ) ;
17-
18- const data = await CourseAPIClient . getModules ( unitId ) ;
19- setCourseModules ( data ) ;
20- } catch ( err : unknown ) {
21- if ( err instanceof Error ) {
22- setError ( err . message ) ;
23- } else {
24- setError ( "An unknown error occurred" ) ;
25- }
26- } finally {
27- setLoading ( false ) ;
22+ setLoading ( true ) ;
23+ setError ( null ) ;
24+
25+ const data = await CourseAPIClient . getModules ( unitId ) ;
26+ setCourseModules ( data ) ;
27+ setModuleDataCache ( ( prevCache ) => {
28+ const newCache = { ... prevCache } ;
29+ newCache [ unitId ] = data ;
30+ return newCache ;
31+ } ) ;
32+ } catch ( err : unknown ) {
33+ if ( err instanceof Error ) {
34+ setError ( err . message ) ;
35+ } else {
36+ setError ( "An unknown error occurred" ) ;
2837 }
29- } ;
38+ } finally {
39+ setLoading ( false ) ;
40+ }
41+ } , [ unitId , moduleDataCache ] ) ;
42+
43+ useEffect ( ( ) => {
44+ if ( ! unitId ) return ; // Prevent API call if unitId is empty
3045
3146 fetchCourseModules ( ) ;
32- } , [ unitId ] ) ;
47+ } , [ fetchCourseModules , unitId ] ) ;
3348
34- return { courseModules, loading, error } ;
49+ return { courseModules, loading, error, moduleDataCache } ;
3550} ;
3651
3752export default useCourseModules ;
0 commit comments