skip to Main Content

onAppear doesn’t trigger

struct ProfileView: View {
    @StateObject var viewModel = ProfileViewViewModel()
    var body: some View {
        NavigationView {
            VStack {
                if let user = viewModel.user {
                    profile(user: user)
                } else {
                    Text("Loading Profile...")
                }
            }
            .navigationTitle("Profile")
        }
        .onAppear {
            viewModel.fetchUser() //this is the problem
        }
        .fullScreenCover(isPresented: $viewModel.showingPreview) {
            PreviewAvatarView()
        }
    }
}

I realized that onAppear didn’t trigger when I dismiss fullscreencover.

2

Answers


  1. Instead of using onAppear you can use task.

    struct ProfileView: View {
        @StateObject var viewModel = ProfileViewViewModel()
        var body: some View {
            NavigationView {
                VStack {
                    if let user = viewModel.user {
                        profile(user: user)
                    } else {
                        Text("Loading Profile...")
                    }
                }
                .navigationTitle("Profile")
            }
            .task(id: viewModel.showingPreview) {
                guard !viewModel.showingPreview else {return} //Check for false
        
                viewModel.fetchUser() //this is the problem
            }
            .fullScreenCover(isPresented: $viewModel.showingPreview) {
                PreviewAvatarView()
            }
        }
    }
    
    

    task will run onAppear and when the Bool is false.

    Login or Signup to reply.
  2. The onAppear doesn’t trigger because your underlying view is not appearing – the view that is covering it is going away, which isn’t the same thing.

    However, fullScreenCover has a rarely-used optional argument, onDismiss, which may fulfil your needs, e.g.:

    .fullScreenCover(
      isPresented: $viewModel.showingPreview,
      onDismiss: { viewModel.fetchUser() }
    ) {
      PreviewAvatarView()
    }
    

    Apple documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search