Skip to content

Commit edcd3b3

Browse files
samatar26markerikson
authored andcommitted
fix: prevent duplicate ids when updating id in unsorted_state_adapter
1 parent 7f76635 commit edcd3b3

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

packages/toolkit/src/entities/tests/state_adapter.test.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,39 @@ describe('createStateOperator', () => {
5858
expect(state2.books.ids.length).toBe(2)
5959
expect(state2.books.entities['b']).toBe(book2)
6060
})
61+
62+
describe("when an id is updated to an existing id's value", () => {
63+
it("only returns one entry for that id in the id's array", () => {
64+
const booksSlice = createSlice({
65+
name: 'books',
66+
initialState: adapter.getInitialState(),
67+
reducers: {
68+
addOne: adapter.addOne,
69+
updateOne: adapter.updateOne,
70+
},
71+
})
72+
73+
const { addOne, updateOne } = booksSlice.actions
74+
75+
const store = configureStore({
76+
reducer: {
77+
books: booksSlice.reducer,
78+
},
79+
})
80+
81+
const book1: BookModel = { id: 'a', title: 'First' }
82+
const book2: BookModel = { id: 'b', title: 'Second' }
83+
store.dispatch(addOne(book1))
84+
store.dispatch(addOne(book2))
85+
86+
const state = store.getState()
87+
expect(state.books.ids).toEqual(['a', 'b'])
88+
89+
store.dispatch(updateOne({ id: 'a', changes: { id: 'b' } }))
90+
91+
const updatedState = store.getState()
92+
expect(updatedState.books.ids).toEqual(['b'])
93+
expect(updatedState.books.entities['b'].title).toBe(book1.title)
94+
})
95+
})
6196
})

packages/toolkit/src/entities/unsorted_state_adapter.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,9 @@ export function createUnsortedStateAdapter<T>(
158158
0
159159

160160
if (didMutateIds) {
161-
state.ids = state.ids.map((id) => newKeys[id] || id)
161+
state.ids = Array.from(
162+
new Set(state.ids.map((id) => newKeys[id] || id))
163+
)
162164
}
163165
}
164166
}

0 commit comments

Comments
 (0)