Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: bug with out of sync index in createMemoryHistory #11509

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 32 additions & 8 deletions packages/native/src/createMemoryHistory.tsx
Expand Up @@ -14,6 +14,26 @@ export function createMemoryHistory() {
let index = 0;
let items: HistoryRecord[] = [];

// @ts-ignore no-unused-vars
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const log = () => {
console.log(
JSON.stringify(
{
index,
indexGetter: history.index,
items: items.map((item, i) => ({
selected: history.index === i ? '<<<<<<<' : undefined,
path: item.path,
id: item.id,
state: item.state?.key || null,
})),
},
null,
4
)
);
};
// Pending callbacks for `history.go(n)`
// We might modify the callback stored if it was interrupted, so we have a ref to identify it
const pending: { ref: unknown; cb: (interrupted?: boolean) => void }[] = [];
Expand Down Expand Up @@ -174,21 +194,20 @@ export function createMemoryHistory() {
// But on Firefox, it seems to take much longer, around 50ms from our testing
// We're using a hacky timeout since there doesn't seem to be way to know for sure
const timer = setTimeout(() => {
const index = pending.findIndex((it) => it.ref === done);
const foundIndex = pending.findIndex((it) => it.ref === done);

if (index > -1) {
pending[index].cb();
pending.splice(index, 1);
if (foundIndex > -1) {
pending[foundIndex].cb();
pending.splice(foundIndex, 1);
}

index = this.index;
}, 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);
index = this.index;

const last = pending.pop();

Expand All @@ -206,12 +225,17 @@ export function createMemoryHistory() {
// Here we normalize it so that only external changes (e.g. user pressing back/forward) trigger the listener
listen(listener: () => void) {
const onPopState = () => {
// Fix createMemoryHistory.index variable's value
// as it may go out of sync when navigating in the browser.
index = this.index;

if (pending.length) {
// This was triggered by `history.go(n)`, we shouldn't call the listener
return;
}

listener();
// log();
};

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