@@ -224,28 +224,42 @@ export default function useLinking(
224
224
let index = history . state ?. index ?? 0 ;
225
225
226
226
if ( previousStateLength === stateLength ) {
227
- // If no new enrties were added to history in our navigation state, we want to replaceState
227
+ // If no new entries were added to history in our navigation state, we want to replaceState
228
228
if ( location . pathname + location . search !== path ) {
229
229
history . replaceState ( { index } , '' , path ) ;
230
230
previousHistoryIndexRef . current = index ;
231
231
}
232
232
} else if ( stateLength > previousStateLength ) {
233
- // If new enrties were added, pushState until we have same length
234
- // This won't be accurate if multiple enrties were added at once, but that's the best we can do
233
+ // If new entries were added, pushState until we have same length
234
+ // This won't be accurate if multiple entries were added at once, but that's the best we can do
235
235
for ( let i = 0 , l = stateLength - previousStateLength ; i < l ; i ++ ) {
236
236
index ++ ;
237
237
history . pushState ( { index } , '' , path ) ;
238
238
}
239
239
240
240
previousHistoryIndexRef . current = index ;
241
241
} else if ( previousStateLength > stateLength ) {
242
- const delta = previousStateLength - stateLength ;
242
+ const delta = Math . min (
243
+ previousStateLength - stateLength ,
244
+ // We need to keep at least one item in the history
245
+ // Otherwise we'll exit the page
246
+ previousHistoryIndexRef . current - 1
247
+ ) ;
243
248
244
- // We need to set this to ignore the `popstate` event
245
- pendingIndexChangeRef . current = index - delta ;
249
+ if ( delta > 0 ) {
250
+ // We need to set this to ignore the `popstate` event
251
+ pendingIndexChangeRef . current = index - delta ;
246
252
247
- // If new enrties were removed, go back so that we have same length
248
- history . go ( - delta ) ;
253
+ // If new entries were removed, go back so that we have same length
254
+ history . go ( - delta ) ;
255
+ } else {
256
+ // We're not going back in history, but the navigation state changed
257
+ // The URL probably also changed, so we need to re-sync the URL
258
+ if ( location . pathname + location . search !== path ) {
259
+ history . replaceState ( { index } , '' , path ) ;
260
+ previousHistoryIndexRef . current = index ;
261
+ }
262
+ }
249
263
}
250
264
} ) ;
251
265
0 commit comments