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
Instead of using
onAppear
you can usetask
.task
will runonAppear
and when theBool
isfalse
.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.:Apple documentation