With TCA, can we create a module that has an access to AppState?

I just exploring TCA and I wonder if we can create an UseCase module that has an access to AppState.

public let searchReducer = Reducer<SearchState, SearchAction, SearchEnvironment> { state, action, environment in
    switch action {
    case .didTapSearch:
        environment.ItemRequestUseCase.start()
           .receive(on: environment.mainQueue())
           .catchToEffect()
           .map(RepositoryAction.dataLoaded)
        return .none
    }
}

By the way, ItemRequestUseCase requires to access to "id" field in AppState. I am thinking something like this.

class ItemRequestUseCase: UseCase {
    let store: Store<AppState>
    init(store: Store<AppState>) {
        self.store = store 
    }

    func start () ... {
        ...
    }
}

Would this be possible?

I'm not sure I understand what you are trying to accomplish, so would need more information, but I can try to answer some of your questions.

First, it certainly is possible to access AppState from other modules, but you would have to extract AppState to its own module so that it is easy to import into those other modules. But, it might not be a good idea to actually do that. Most likely other modules don't need access to all of AppState, and instead just a small part of it. So, you could just extract those small pieces to module(s) and then import that into your other features.

Also, this code has a problem as written now:

    case .didTapSearch:
        environment.ItemRequestUseCase.start()
           .receive(on: environment.mainQueue())
           .catchToEffect()
           .map(RepositoryAction.dataLoaded)
        return .none

This code is constructing an effect but does not actually return it, and instead returns .none. That is most likely not what you intend to do. You should be returning that effect from the reducer.

1 Like

I was also wondering if this is a recommended way but thank you, you already answered. Thank you!
I am moving forward with approach took in this example.

https://github.com/pointfreeco/swift-composable-architecture/blob/main/Examples/CaseStudies/SwiftUICaseStudies/01-GettingStarted-SharedState.swift