Apply a partial collection response
A fulfilled API response contains several records that should be inserted or replace records with matching IDs.
Redux Toolkit · Module
adapter.setMany adds or replaces multiple entities in a normalized entity-adapter state. It accepts either an array of entities or an ID-keyed record.
setMany applies a collection of entities to an entity-adapter state. Each supplied item is identified through the adapter's ID configuration and is inserted when absent or replaces the matching existing entity.
adapter.setMany(state, entities)import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
type Todo = { id: string; text: string; done: boolean }
const todos = createEntityAdapter<Todo>()
const slice = createSlice({
name: 'todos',
initialState: todos.getInitialState(),
reducers: {
replaceSome(state, action: { payload: Todo[] }) {
todos.setMany(state, action.payload)
}
}
})
const state = slice.reducer(undefined, {
type: 'todos/replaceSome',
payload: [{ id: 'a', text: 'Read docs', done: true }]
})
console.log(state.entities.a)Creates an entity adapter and uses setMany as a case-reducer helper to add or replace the supplied entities.
A fulfilled API response contains several records that should be inserted or replace records with matching IDs.
A slice receives a batch of entities and should retain unrelated entities already in state.
A reducer needs to update normalized state through a generated entity-adapter helper.
setMany accepts multiple entities and adds or replaces them in the adapter-managed normalized state. It can receive either an array or an ID-keyed record.
Follow-up: How would you preserve existing entities not included in the input? Use setMany rather than setAll, because setMany changes only the supplied IDs.
The adapter determines each entity's ID using its configured identity behavior, then updates the normalized collection. Existing matching entries are replaced, while new IDs are inserted.
Follow-up: What if entities use a field other than id? Configure the adapter with selectId so the adapter can derive each entity's identity.
The method is generated by createEntityAdapter and can be used as a case reducer or as a mutating helper inside createSlice or createReducer. The surrounding Redux Toolkit reducer setup handles immutable state updates.
Follow-up: Why might a sorted adapter change the IDs array after setMany? A configured sortComparer can maintain IDs in sorted order as the collection changes.
createEntityAdapteraddManysetOnesetAllupsertManygetInitialState