1
1
import _ from 'lodash' ;
2
2
import React , { useMemo } from 'react' ;
3
- import { matchPath , useLocation } from 'react-router-dom' ;
3
+ import { matchPath , useHistory } from 'react-router-dom' ;
4
4
import { ConfigState } from '../../redux/configSlice' ;
5
5
import { useTypedSelector } from '../../redux/reducers/reducers' ;
6
6
import { getCluster , getClusterGroup , getClusterPrefixedPath } from '../util' ;
@@ -106,15 +106,13 @@ export function useClustersConf(): ConfigState['allClusters'] {
106
106
}
107
107
108
108
export function useCluster ( ) {
109
- // Make sure we update when changing clusters.
110
- // @todo : We need a better way to do this.
111
- const location = useLocation ( ) ;
109
+ const history = useHistory ( ) ;
112
110
113
111
// This function is similar to the getCluster() but uses the location
114
112
// meaning it will return the URL from whatever the router used it (which
115
113
// is more accurate than getting it from window.location like the former).
116
114
function getClusterFromLocation ( ) : string | null {
117
- const urlPath = location ?. pathname ;
115
+ const urlPath = history . location ?. pathname ;
118
116
const clusterURLMatch = matchPath < { cluster ?: string } > ( urlPath , {
119
117
path : getClusterPrefixedPath ( ) ,
120
118
} ) ;
@@ -124,11 +122,13 @@ export function useCluster() {
124
122
const [ cluster , setCluster ] = React . useState < string | null > ( getClusterFromLocation ( ) ) ;
125
123
126
124
React . useEffect ( ( ) => {
127
- const currentCluster = getClusterFromLocation ( ) ;
128
- if ( cluster !== currentCluster ) {
129
- setCluster ( currentCluster ) ;
130
- }
131
- } , [ cluster , location ] ) ;
125
+ // Listen to route changes
126
+ return history . listen ( ( ) => {
127
+ const newCluster = getClusterFromLocation ( ) ;
128
+ // Update the state only when the cluster changes
129
+ setCluster ( currentCluster => ( newCluster !== currentCluster ? newCluster : currentCluster ) ) ;
130
+ } ) ;
131
+ } , [ history ] ) ;
132
132
133
133
return cluster ;
134
134
}
0 commit comments