Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/history-forward-entries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/history': patch
---

Avoid temporary arrays when replacing forward memory-history entries.
10 changes: 5 additions & 5 deletions packages/history/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -663,13 +663,13 @@ export function createMemoryHistory(
getLength: () => entries.length,
pushState: (path, state) => {
// Removes all subsequent entries after the current index to start a new branch
index = index < entries.length - 1 ? index + 1 : entries.length
states[index] = state
entries[index] = path
if (index < entries.length - 1) {
entries.splice(index + 1)
states.splice(index + 1)
entries.length = index + 1
states.length = index + 1
}
states.push(state)
entries.push(path)
index = Math.max(entries.length - 1, 0)
},
replaceState: (path, state) => {
states[index] = state
Expand Down
32 changes: 32 additions & 0 deletions packages/history/tests/createMemoryHistory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,38 @@ describe('createMemoryHistory', () => {
expect(history.location.pathname).toBe('/b')
})

test('discards forward entries and their state when pushing a new branch', () => {
const initialEntries = ['/']
const history = createMemoryHistory({ initialEntries })
history.push('/kept', { marker: 'kept' })
const keptState = history.location.state
history.push('/discarded-first', { marker: 'discarded-first' })
history.push('/discarded-last', { marker: 'discarded-last' })
history.go(-2)
history.push('/new', { marker: 'new' })

expect(initialEntries).toEqual(['/', '/kept', '/new'])
expect(history.length).toBe(3)
expect(history.location.pathname).toBe('/new')
expect(history.location.state).toMatchObject({
__TSR_index: 2,
marker: 'new',
})
const newState = history.location.state

history.forward()
expect(history.location.pathname).toBe('/new')
expect(history.location.state).toBe(newState)

history.back()
expect(history.location.pathname).toBe('/kept')
expect(history.location.state).toBe(keptState)

history.forward()
expect(history.location.pathname).toBe('/new')
expect(history.location.state).toBe(newState)
})

test('length', () => {
const history = createMemoryHistory()
expect(history.length).toBe(1)
Expand Down
Loading