ReactComponentKit / Redux

Manage iOS App state with Redux and Async/Await :)
MIT License
24 stars 0 forks source link

isLoading state async function #10

Closed DistroDan closed 2 years ago

DistroDan commented 2 years ago

Hello. Awesome library. I love how simple it is to use for state management. One question I have is how you'd go about a isLoading state? I'd like to use loading state to display a spinner to show that an action is loading when a button is pressed. In my store I've created the following @Published var isLoading: Bool = false which has a mutation private func SET_LOADING(authState: inout AuthState, payload: Bool) { authState.isLoading = payload } I currently have an async function that signs a user in using an action and commiting the result which works perfectly. When I try to change the loading status though using the state it is not reflected. Wondering if this is something that should be included in the middleware? Here is what I currently have

Screen Shot 2022-03-07 at 11 04 30 PM
skyfe79 commented 2 years ago

@DistroDan Hi! DistroDan. First of all, thanks for your great feedback. I've updated an example to show the loading state with ProgressView. There is no need to use middleware for async operation. I think this PR could help you. https://github.com/ReactComponentKit/ReduxCounter/pull/1

func fetchContentValue() async { 
    do {
        commit(mutation: SET_IS_LOADING, payload: true)
        let (data, _) = try await URLSession.shared.data(from: URL(string: "https://www.facebook.com")!)
        let value = String(data: data, encoding: .utf8) ?? ""
        commit(mutation: SET_ERROR, payload: nil)
        commit(mutation: SET_CONTENT_VALUE, payload: value)
        commit(mutation: SET_IS_LOADING, payload: false)
    } catch {
        commit(mutation: SET_IS_LOADING, payload: false)
        commit(mutation: SET_ERROR, payload: error.localizedDescription)
    }
}

fetchContentValue() method setted the isLoading state when start async operation and finished it. ContentStore reflects the isLoading state to isLoading Publisher on the computed method of ContentStore and ComposeAppStore reflect isLoading Publisher to ProgressUI View.

It is important to chain the publishers when you composing stores on SwiftUI.

Thanks & best regards,

DistroDan commented 2 years ago

@skyfe79 Thanks so much. This is a great example and is exactly what I needed.

Regards

skyfe79 commented 2 years ago

@DistroDan Great Thanks! 😄