Hello. I want to do a fetch when a view loads. In UIKit I would have used viewDidLoad to do this but in SwiftUI we only have onAppear and task. Is that by design, and if so, what is the recommended way to fetch data?
I wrote a little blog post for a workaround describing the issue and the found solution, but I presume there is a better way. https://www.ludafux.com/post/viewdidload_doppelganger
Best Regards, Luda
task and onAppear have the same semantics for when they are executed which is before the first view is shown. However, task has a few more capabilities:
- task(priority:_:) uses an async closure, making it more convenient for triggering asynchronous tasks without needing to use Swift's Task within onAppear and it provides additional parameters for fine-grained task management, such as configuring its priority and using its id to cancel and restart tasks if needed.
The UIKit viewDidAppear(:) and viewDidDisappear(:) methods are invoked specifically around when views become visible/not visible to the user, whereas the SwiftUI calls to onAppear or task are tied more to when the views are constructed/torn down, rather than visually presented.