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
14 changes: 5 additions & 9 deletions packages/history/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,38 +366,34 @@ export function createMemoryHistory(
): RouterHistory {
const entries = opts.initialEntries
let index = opts.initialIndex ?? entries.length - 1
let currentState = {
key: createRandomKey(),
} as HistoryState
const states = entries.map(() => ({}) as HistoryState)

const getLocation = () => parseHref(entries[index]!, currentState)
const getLocation = () => parseHref(entries[index]!, states[index])

return createHistory({
getLocation,
getLength: () => entries.length,
pushState: (path, state) => {
currentState = state
// Removes all subsequent entries after the current index to start a new branch
if (index < entries.length - 1) {
entries.splice(index + 1)
states.splice(index + 1)
}
states.push(state)
entries.push(path)
index = Math.max(entries.length - 1, 0)
},
replaceState: (path, state) => {
currentState = state
states[index] = state
entries[index] = path
},
back: () => {
currentState = assignKey(currentState)
index = Math.max(index - 1, 0)
},
forward: () => {
currentState = assignKey(currentState)
index = Math.min(index + 1, entries.length - 1)
},
go: (n) => {
currentState = assignKey(currentState)
index = Math.min(Math.max(index + n, 0), entries.length - 1)
},
createHref: (path) => path,
Expand Down
12 changes: 12 additions & 0 deletions packages/history/tests/createMemoryHistory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,16 @@ describe('createMemoryHistory', () => {
history.push('/c')
expect(history.length).toBe(2)
})

test('state', () => {
const history = createMemoryHistory()
history.push('/a', { i: 1 })
expect((history.location.state as any).i).toBe(1)
history.replace('/b', { i: 2 })
expect((history.location.state as any).i).toBe(2)
history.back()
expect((history.location.state as any).i).toBeUndefined()
history.push('/c', { i: 3 })
expect((history.location.state as any).i).toBe(3)
})
})