Batch server synchronization
Several records from one API response need partial field changes.
Redux Toolkit · Module
adapter.updateMany applies partial, shallow updates to multiple entities in a normalized entity state. Each update targets an ID and supplies changed fields through changes.
Call the adapter method with entity state and an array of update objects. Each object names an entity through id and supplies partial fields in changes; matching entities are shallowly updated, while repeated IDs are consolidated with later values taking precedence.
updateMany<S extends EntityState<T>>(state: S, updates: Update<T>[]): S| Name | Type | Description |
|---|---|---|
state | EntityState<T> | The normalized entity state to modify. |
updates | Update<T>[] | An array of update objects; each identifies an entity and supplies partial fields in changes. |
The updated entity state, preserving the state type.
import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'
type User = { id: string; name: string; role: string }
const usersAdapter = createEntityAdapter<User>()
const usersSlice = createSlice({
name: 'users',
initialState: usersAdapter.getInitialState(),
reducers: {
usersUpdated: usersAdapter.updateMany,
},
})
usersSlice.reducer(usersSlice.getInitialState(), {
type: 'users/usersUpdated',
payload: [
{ id: '1', changes: { role: 'admin' } },
{ id: '2', changes: { name: 'Ada Lovelace' } },
],
})Registers updateMany as a slice reducer; dispatching an array of update objects applies shallow changes to every matching entity.
Several records from one API response need partial field changes.
A slice reducer receives one action containing changes for multiple entities.
Normalized records need targeted edits without rebuilding the collection.
It accepts the entity state and an array of Update objects, returning the updated state. Each update identifies an entity by id and provides partial fields in changes, which are applied shallowly.
Follow-up: What happens when two updates target the same ID? They are merged into one update, with later updates overwriting earlier values.
It can be used as a case reducer in createReducer or createSlice, or as a mutating helper within another reducer. When used as a slice reducer, the action payload contains the updates array.
Follow-up: Why is the helper suitable for normalized state? The adapter operates on the generated ids/entities structure and targets records by ID.
The changes object is merged shallowly into each matching entity. A nested object supplied in changes replaces the existing nested object instead of being recursively merged.
Follow-up: What design follows from this behavior? Keep entity records relatively flat or construct complete replacement values for nested fields.
createEntityAdapterEntityStateUpdateupdateOneupsertManycreateSlice