My question is a conceptual question.
I have the following code:
struct CategoriesList : View {
@State pri
The SwiftUI community hasn't really established any best-practices yet because the technology is so new. My answer is based off of what I've seen from different WWDC19 sessions.
First, create a BindableObject
with a categories
property. Then write your network request code and set self.categories
to your newly downloaded categories.
import SwiftUI
import Combine
final class CategoryStore: BindableObject {
var didChange = PassthroughSubject()
var categories = [String]()
init() {
// TODO: Fetch categories from API
self.categories = ["A", "B", "C"]
}
}
Then, add CategoryStore
to View
and use it with List
to iterate over the categories.
import SwiftUI
struct ContentView : View {
@ObjectBinding private var store = CategoryStore()
var body: some View {
List(store.categories.identified(by: \.self)) { category in
Text(category)
}
}
}
Whenever the categories
property updates, your UI will update with the new categories (tysm Combine)