You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The synchronous initializer is a sensible default, but if your app's needs dictate displaying data only once you've loaded all of the necessary items the asynchronous initializers are there to help.
116
116
117
+
## Observing Store Loading State
118
+
119
+
You can manually observe the loading state of a ``Store`` as we do in `getItems()` above, but Boutique also provides a ``onStoreDidLoad`` function to observe the loading state of a ``Store`` in SwiftUI.
120
+
121
+
```swift
122
+
structContentView: View {
123
+
@Storedvar items: [Item]
124
+
@Statevar itemsHaveLoaded =false
125
+
126
+
var body: some View {
127
+
VStack {
128
+
AlwaysVisibleBanner()
129
+
130
+
ifself.itemsHaveLoaded {
131
+
ifself.items.isEmpty {
132
+
EmptyStateView()
133
+
} else {
134
+
ItemsView(items: self.items)
135
+
}
136
+
} else {
137
+
LoadingStateView()
138
+
}
139
+
}
140
+
.onStoreDidLoad(
141
+
self.$items,
142
+
update: $itemsHaveLoaded,
143
+
onError: { error in
144
+
log.error("Failed to load items", error)
145
+
}
146
+
)
147
+
}
148
+
}
149
+
```
150
+
151
+
This allows for a clean separation of Views to display across three different states:
152
+
- When the Store has finished loading and has items
153
+
- When the Store has finished loading and has no items
154
+
- When the Store is loading (and implicitly has no items)
155
+
156
+
You can also choose to use the closure-oriented variant of ``onStoreDidLoad`` to perform any additional logic when the ``Store`` has finished loading. Patterns like MVVM choose to isolate this logic ViewModel, and you can still choose to do that, but exposing this method on a View provides more flexibility to work with your preferred architecture. In the example below we will filter the items in a ``Store`` based on some criteria, to display only the relevant items in our View.
157
+
158
+
```swift
159
+
.onStoreDidLoad(
160
+
self.$items,
161
+
onLoad: {
162
+
self.items=self.filteredItems(self.items)
163
+
},
164
+
onError: { error in
165
+
log.error("Failed to load items", error)
166
+
}
167
+
)
168
+
```
169
+
117
170
## Further Exploration, @Stored And More
118
171
119
172
Building an app using the ``Store`` can be really powerful because it leans into SwiftUI's state-driven architecture, while providing you with offline-first capabilities, realtime updates across your app, with almost no additional code required.
0 commit comments