scope(state:action:)

Scopes the store to one that exposes child state and actions.

Store.swift:299
@MainActor func scope<ChildState, ChildAction>(state: KeyPath<State, ChildState>, action: CaseKeyPath<Action, ChildAction>) -> Store<ChildState, ChildAction>

Parameters

state

A key path from State to ChildState.

action

A case key path from Action to ChildAction.

Returns

A new store with its domain (state and action) transformed.

This can be useful for deriving new stores to hand to child views in an application. For example:

@Reducer
struct AppFeature {
  @ObservableState
  struct State {
    var login: Login.State
    // ...
  }
  enum Action {
    case login(Login.Action)
    // ...
  }
  // ...
}

// A store that runs the entire application.
let store = Store(initialState: AppFeature.State()) {
  AppFeature()
}

// Construct a login view by scoping the store
// to one that works with only login domain.
LoginView(
  store: store.scope(state: \.login, action: \.login)
)

Scoping in this fashion allows you to better modularize your application. In this case, LoginView could be extracted to a module that has no access to AppFeature.State or AppFeature.Action.