@@ -7,8 +7,9 @@ import { Album } from './FeaturedAlbums';
77// STATE - This defines the type of data maintained in the Redux store.
88
99export interface GenreDetailsState {
10- isLoaded : boolean ;
10+ requestedGenreId : number ;
1111 albums : Album [ ] ;
12+ isLoaded : boolean ;
1213}
1314
1415// -----------------
@@ -25,7 +26,7 @@ class RequestGenreDetails extends Action {
2526
2627@typeName ( "RECEIVE_GENRE_DETAILS" )
2728class ReceiveGenreDetails extends Action {
28- constructor ( public albums : Album [ ] ) {
29+ constructor ( public genreId : number , public albums : Album [ ] ) {
2930 super ( ) ;
3031 }
3132}
@@ -36,24 +37,31 @@ class ReceiveGenreDetails extends Action {
3637
3738export const actionCreators = {
3839 requestGenreDetails : ( genreId : number ) : ActionCreator => ( dispatch , getState ) => {
39- fetch ( `/api/genres/${ genreId } /albums` )
40- . then ( results => results . json ( ) )
41- . then ( albums => dispatch ( new ReceiveGenreDetails ( albums ) ) ) ;
42-
43- dispatch ( new RequestGenreDetails ( genreId ) ) ;
40+ // Only load if it's not already loaded (or currently being loaded)
41+ if ( genreId !== getState ( ) . genreDetails . requestedGenreId ) {
42+ fetch ( `/api/genres/${ genreId } /albums` )
43+ . then ( results => results . json ( ) )
44+ . then ( albums => {
45+ // Only replace state if it's still the most recent request
46+ if ( genreId === getState ( ) . genreDetails . requestedGenreId ) {
47+ dispatch ( new ReceiveGenreDetails ( genreId , albums ) ) ;
48+ }
49+ } ) ;
50+
51+ dispatch ( new RequestGenreDetails ( genreId ) ) ;
52+ }
4453 }
4554} ;
4655
4756// ----------------
4857// REDUCER - For a given state and action, returns the new state. To support time travel, this must not mutate the old state.
4958// For unrecognized actions, must return the existing state (or default initial state if none was supplied).
50- const unloadedState : GenreDetailsState = { isLoaded : false , albums : [ ] } ;
5159export const reducer : Reducer < GenreDetailsState > = ( state , action ) => {
5260 if ( isActionType ( action , RequestGenreDetails ) ) {
53- return unloadedState ;
61+ return { requestedGenreId : action . genreId , albums : [ ] , isLoaded : false } ;
5462 } else if ( isActionType ( action , ReceiveGenreDetails ) ) {
55- return { isLoaded : true , albums : action . albums } ;
63+ return { requestedGenreId : action . genreId , albums : action . albums , isLoaded : true } ;
5664 } else {
57- return state || unloadedState ;
65+ return state || { requestedGenreId : null as number , albums : [ ] , isLoaded : false } ;
5866 }
5967} ;
0 commit comments