I recently had someone ask me how I handled fetching and rendering data from a REST API in a SwiftUI view.
If you’re coming from something like React, it’s actually handled differently. We can’t just fire off a request in
onAppear, and update some
@State. Awkwardness with
structs not being mutable, etc etc etc.
Luckily SwiftUI has some constructs that can help :) I won’t be going over how to make GET requests or whatever in detail, though I like to use Just.
Firsts up, let’s have a view
So, how do we get the
user object here loaded?
Actually no. There’s something called an ObservableObject. This is an object with
@Published properties. If a
@Published property is updated, any view containing this object will have an update triggered.
An example will probably illustrate this more effectively
The view essentially “observes” something “observable” -
@ObservableObject. As soon as a
@Published property is updated on something we are observing, a re-render is triggered and the view updates!
Hopefully this clears things up!