Map a custom identifier field
Entities use a primary-key property named something other than id.
Redux Toolkit · Type Alias
IdSelector<T> describes a function that extracts an entity's unique EntityId from a model. It is used by createEntityAdapter, with entity.id as the default extraction rule.
IdSelector<T> is the function type used to obtain an entity's unique identifier from a model. Pass one to createEntityAdapter when the identifier is not stored in the conventional id property.
export type IdSelector<T> = (model: T) => EntityId| Name | Type | Description |
|---|---|---|
model | T | The model whose unique identifier should be extracted. |
EntityId
import { createEntityAdapter } from '@reduxjs/toolkit'
type User = { userId: string; name: string }
const usersAdapter = createEntityAdapter<User>({
selectId: (user) => user.userId,
})
const state = usersAdapter.getInitialState()
const nextState = usersAdapter.addOne(state, {
userId: 'u1',
name: 'Ada',
})
console.log(usersAdapter.getSelectors().selectById(nextState, 'u1'))The custom selector extracts each user's unique identifier so the adapter can store and retrieve entities by that identifier.
Entities use a primary-key property named something other than id.
A typed entity adapter needs a reusable contract for ID extraction.
Normalized state needs stable keys for entity lookup and generated selectors.
IdSelector<T> is a function accepting one model of type T and returning an EntityId. It supplies the identifier that the entity adapter uses for normalized storage and lookup.
Follow-up: What should you do if the identifier is not named id? Provide selectId, such as selectId: user => user.userId, when creating the adapter.
The adapter uses the selector to determine each entity's unique ID. The default behavior uses entity.id, so a custom selector is needed for another identifier field.
Follow-up: How does the selected ID affect adapter selectors? It becomes the key used by selectors such as selectById to find an entity.
An IdSelector maps a model to an EntityId, allowing createEntityAdapter to normalize entities into IDs and an entity lookup table. The resulting adapter can then generate selectors for that normalized state.
Follow-up: Which generated selector retrieves one entity? selectById accepts the state and an EntityId, returning the matching entity or undefined.
createEntityAdapterselectIdEntityIdselectByIdselectAllgetSelectors