Skip to content

Initial actions #3624

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Sources/ComposableArchitecture/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,13 @@ public final class Store<State, Action> {
///
/// - Parameters:
/// - initialState: The state to start the application in.
/// - initialAction: An action to send the store when it is created.
/// - reducer: The reducer that powers the business logic of the application.
/// - prepareDependencies: A closure that can be used to override dependencies that will be accessed
/// by the reducer.
public convenience init<R: Reducer<State, Action>>(
initialState: @autoclosure () -> R.State,
initialAction: @autoclosure () -> R.Action? = nil,
@ReducerBuilder<State, Action> reducer: () -> R,
withDependencies prepareDependencies: ((inout DependencyValues) -> Void)? = nil
) {
Expand All @@ -182,6 +184,9 @@ public final class Store<State, Action> {
initialState: initialState,
reducer: reducer.dependency(\.self, dependencies)
)
if let initialAction = initialAction() {
send(initialAction)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How can we send initial actions to stores created by store.scope(…)?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. It's rather uncommon outside of tests to use the store's initialiser directly.

}
}

init() {
Expand Down
11 changes: 11 additions & 0 deletions Tests/ComposableArchitectureTests/StoreTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1213,6 +1213,17 @@ final class StoreTests: BaseTCATestCase {
}
}
}

@MainActor
func testInitialAction() async {
let store = Store<Int, Void>(initialState: 0, initialAction: ()) {
Reduce<Int, Void> { state, _ in
state += 1
return .none
}
}
XCTAssertEqual(store.currentState, 1)
}
}

#if canImport(Testing)
Expand Down
Loading