Skip to content

Commit fb84805

Browse files
authored
fix: fix navigation when going back and forth in history on web (react-navigation#9970)
closes react-navigation#9408 fixes react-navigation#9128
1 parent 5966e15 commit fb84805

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

packages/native/src/useLinking.tsx

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,16 @@ const createMemoryHistory = () => {
9898

9999
const id = window.history.state?.id ?? nanoid();
100100

101-
if (items.length) {
102-
items[index] = { path, state, id };
101+
if (!items.length || items.findIndex((item) => item.id === id) < 0) {
102+
// There are two scenarios for creating an array with only one history record:
103+
// - When loaded id not found in the items array, this function by default will replace
104+
// the first item. We need to keep only the new updated object, otherwise it will break
105+
// the page when navigating forward in history.
106+
// - This is the first time any state modifications are done
107+
// So we need to push the entry as there's nothing to replace
108+
items = [{ path, state, id }];
103109
} else {
104-
// This is the first time any state modifications are done
105-
// So we need to push the entry as there's nothing to replace
106-
items.push({ path, state, id });
110+
items[index] = { path, state, id };
107111
}
108112

109113
window.history.replaceState({ id }, '', path);
@@ -179,6 +183,13 @@ const createMemoryHistory = () => {
179183
}, 100);
180184

181185
const onPopState = () => {
186+
const id = window.history.state?.id;
187+
const currentIndex = items.findIndex((item) => item.id === id);
188+
189+
// Fix createMemoryHistory.index variable's value
190+
// as it may go out of sync when navigating in the browser.
191+
index = Math.max(currentIndex, 0);
192+
182193
const last = pending.pop();
183194

184195
window.removeEventListener('popstate', onPopState);

0 commit comments

Comments
 (0)