In SwiftUI, I have a `TextField` where the user ca...
# multiplatform
l
In SwiftUI, I have a
TextField
where the user can input text, which is bound to a property. However, I also want to observe a KMP ViewModel's
StateFlow
which can update the text in the
TextField
. I'm using SKIE. How can I achieve it?
t
We were just looking into this for SKIE. One way to do it:
Copy code
struct ExampleView: View {
  let viewModel = ExampleViewModel()

  var body: some View {
    Observing(viewModel.textFieldInput) { input in
      TextField("Prompt", text: Binding(get: { input }, set: { viewModel.textFieldInput.value = $0 })
    }
  }
}
l
Thanks!
t
Let me know if that works for you. There are other possibilities and we're even looking at ways to implement it in SKIE directly
l
I solved it like this:
Copy code
struct MainView: View {

    private let viewModel = ViewModelProvider.shared.getMainViewModel()
    @State private var transactionId: String = ""

    var body: some View {
                TextField("Transaction ID:", text: $transactionId).collect(flow: viewModel.uiState) { uiState in
                    transactionId = uiState.transactionId ?? ""
                }
        }
    }
t
Yeah, that was the other way I'd suggest, but you still need to add the
Binding
so that it updates the
viewModel.uiState
l
True
t
Copy code
struct MainView: View {

    private let viewModel = ViewModelProvider.shared.getMainViewModel()
    @State private var transactionId: String = ""

    var body: some View {
                TextField("Transaction ID:", text: Binding(get: { transactionId }, set: { viewModel.setTransactionID($0) }).collect(flow: viewModel.uiState) { uiState in
                    transactionId = uiState.transactionId ?? ""
                }
        }
    }
l
Thank you for the quick help!