Skip to content

Commit 6bdf6ae

Browse files
committed
fix: handle in-page go back when there's no history
fixes react-navigation#7852
1 parent e2bcf51 commit 6bdf6ae

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

packages/native/src/useLinking.tsx

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -224,28 +224,42 @@ export default function useLinking(
224224
let index = history.state?.index ?? 0;
225225

226226
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
228228
if (location.pathname + location.search !== path) {
229229
history.replaceState({ index }, '', path);
230230
previousHistoryIndexRef.current = index;
231231
}
232232
} 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
235235
for (let i = 0, l = stateLength - previousStateLength; i < l; i++) {
236236
index++;
237237
history.pushState({ index }, '', path);
238238
}
239239

240240
previousHistoryIndexRef.current = index;
241241
} 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+
);
243248

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;
246252

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+
}
249263
}
250264
});
251265

0 commit comments

Comments
 (0)