Skip to main content

ForEach

The forEach 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

Parameters:
  • toElementsState: A writable key path from parent state to an IdentifiedArray of child state
  • toElementAction: A case path from parent action to an IdentifiedAction of child actions
  • element: A reducer builder closure that describes the child reducer to run for each element
Returns: A reducer that combines the child reducer with the parent reducer

IdentifiedAction

A wrapper type for actions that target specific elements in a collection by their ID.

IdentifiedActionOf

A convenience type alias for identified actions of a reducer whose state is Identifiable.

Usage

Basic list management

With network effects

Order of Operations

The forEach operator enforces a specific order:
  1. Element reducer runs first - The child reducer processes the action
  2. Parent reducer runs second - The parent’s core logic executes
This ordering ensures that child reducers can handle their actions before a parent might remove them from the collection.

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

If forEach receives an action for an element that doesn’t exist in the collection, it will emit a runtime warning:
This can happen when:
  • 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 IdentifiedArray from the swift-identified-collections library
  • Element state must have a stable, unique ID
  • Actions must be wrapped in IdentifiedAction to specify which element they target

See Also

  • IdentifiedArray - Collection type that provides safe ID-based access
  • ifLet - For embedding reducers over optional state
  • Scope - For embedding single child reducers