Skip to content

Commit

Permalink
fix: fix navigation when going back and forth in history on web (#9970)
Browse files Browse the repository at this point in the history
closes #9408
fixes #9128
  • Loading branch information
satya164 committed Sep 26, 2021
1 parent 5966e15 commit fb84805
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions packages/native/src/useLinking.tsx
Expand Up @@ -98,12 +98,16 @@ const createMemoryHistory = () => {

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

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

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

const onPopState = () => {
const id = window.history.state?.id;
const currentIndex = items.findIndex((item) => item.id === id);

// Fix createMemoryHistory.index variable's value
// as it may go out of sync when navigating in the browser.
index = Math.max(currentIndex, 0);

const last = pending.pop();

window.removeEventListener('popstate', onPopState);
Expand Down

0 comments on commit fb84805

Please sign in to comment.