CodexBloom - Programming Q&A Platform

how to to dismiss SwiftUI modal after successful data submission using Combine in iOS 17

👀 Views: 46 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
SwiftUI Combine iOS17 Swift

I'm reviewing some code and I'm a bit lost with After trying multiple solutions online, I still can't figure this out... I'm sure I'm missing something obvious here, but I'm working with an scenario where I need to seem to dismiss a modal view after successfully submitting data using Combine in my SwiftUI application. I'm using a `@State` variable to control the presentation of the modal, but after the submission completes, the modal stays open despite the state changing. Here's the relevant part of my code: ```swift import SwiftUI import Combine struct ContentView: View { @State private var isModalPresented = false @State private var viewModel = MyViewModel() var body: some View { Button("Show Modal") { isModalPresented.toggle() } .sheet(isPresented: $isModalPresented) { ModalView(viewModel: viewModel, isPresented: $isModalPresented) } } } struct ModalView: View { @ObservedObject var viewModel: MyViewModel @Binding var isPresented: Bool var body: some View { VStack { TextField("Enter Data", text: $viewModel.data) Button("Submit") { viewModel.submitData() } } .onReceive(viewModel.$isSuccess) { success in if success { isPresented = false // This line does not dismiss the modal } } } } class MyViewModel: ObservableObject { @Published var data: String = "" @Published var isSuccess: Bool = false func submitData() { // Simulating a network operation dispatchQueue.global().asyncAfter(deadline: .now() + 1) { // Assuming submission is successful DispatchQueue.main.async { self.isSuccess = true } } } } ``` I've confirmed that the `isSuccess` property is being set to true after the submission completes, but the modal doesn't close. I also tried using `DispatchQueue.main.async {}` around `isPresented = false`, but that didn't solve the question either. Is there something I'm missing or a better practice for handling modal dismissals in SwiftUI with Combine? Any insights would be greatly appreciated! For context: I'm using Swift on Ubuntu. Any help would be greatly appreciated! For context: I'm using Swift on Ubuntu 20.04. Any help would be greatly appreciated!