ForEach
TheforEach operator embeds a child reducer in a parent domain that operates on elements of a collection in parent state. It’s used when a parent feature manages a list of child features and needs to run child logic for actions targeting specific elements.
Method Signature
toElementsState: A writable key path from parent state to anIdentifiedArrayof child statetoElementAction: A case path from parent action to anIdentifiedActionof child actionselement: A reducer builder closure that describes the child reducer to run for each element
Related Types
IdentifiedAction
IdentifiedActionOf
Identifiable.
Usage
Basic list management
With network effects
Order of Operations
TheforEach operator enforces a specific order:
- Element reducer runs first - The child reducer processes the action
- Parent reducer runs second - The parent’s core logic executes
Automatic Effect Cancellation
When an element is removed from the collection,forEach automatically cancels all effects associated with that element. This prevents memory leaks and ensures that long-running effects don’t continue after their associated state is gone.
Runtime Warnings
IfforEach receives an action for an element that doesn’t exist in the collection, it will emit a runtime warning:
- A parent reducer removed the element before the forEach ran
- An in-flight effect emitted an action after the element was removed
- An action was sent for a non-existent element ID
Requirements
- Uses
IdentifiedArrayfrom the swift-identified-collections library - Element state must have a stable, unique ID
- Actions must be wrapped in
IdentifiedActionto specify which element they target
See Also
IdentifiedArray- Collection type that provides safe ID-based accessifLet- For embedding reducers over optional stateScope- For embedding single child reducers