I am creating a slice with a reducer that selects an entity by id.
Only one entity must be selected at a time, so the reducer deselects any previously selected entity, before selecting the new one.
I am maintaining the id of the selected item in state.
This does not 'feel' right, as the reducer is changing three things:
- Deselects previously selected entity
- Selects the new entity
- Sets the state.selectedItemId to the newly selected entity id
Can anyone suggest a better way to achieve this?
const itemsAdapter = createEntityAdapter();
const itemsSlice = createSlice({
name: 'items',
initialState: itemsAdapter.getInitialState({
selectedItemId: null
}),
reducers: {
itemSelected: (state, action) => {
if (state.selectedItemId) {
state.entities[state.selectedItemId].selected = false;
}
state.entities[action.payload].selected = true;
state.selectedItemId = action.payload;
}
}
});