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,45 @@ 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+ if ( moduleDataCache [ unitId ] ) {
17+ setCourseModules ( moduleDataCache [ unitId ] ) ;
18+ return ;
19+ }
1220
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 ) ;
21+ setLoading ( true ) ;
22+ setError ( null ) ;
23+
24+ const data = await CourseAPIClient . getModules ( unitId ) ;
25+ setCourseModules ( data ) ;
26+ setModuleDataCache ( ( prevCache ) => {
27+ const newCache = { ... prevCache } ;
28+ newCache [ unitId ] = data ;
29+ return newCache ;
30+ } ) ;
31+ } catch ( err : unknown ) {
32+ if ( err instanceof Error ) {
33+ setError ( err . message ) ;
34+ } else {
35+ setError ( "An unknown error occurred" ) ;
2836 }
29- } ;
37+ } finally {
38+ setLoading ( false ) ;
39+ }
40+ } , [ unitId , moduleDataCache ] ) ;
41+
42+ useEffect ( ( ) => {
43+ if ( ! unitId ) return ; // Prevent API call if unitId is empty
3044
3145 fetchCourseModules ( ) ;
32- } , [ unitId ] ) ;
46+ } , [ fetchCourseModules , unitId ] ) ;
3347
34- return { courseModules, loading, error } ;
48+ return { courseModules, loading, error, moduleDataCache } ;
3549} ;
3650
3751export default useCourseModules ;
0 commit comments