I wanted to get the API from the site and show it to the ContentView.
However, the function that receives the API that I wrote in the onAppear function attached to the List does not work.
So when access the array where you store the data, this app stops because it said you accessed nil.
var body: some View {
Color.pink.opacity(0.2)
List(weatherFetcher.weathers.first!.response.body.items.item, id: .id) { weather in
VStack(alignment: .leading) {
Text(weather.category)
.font(.headline)
Text(weather.fcstValue)
.font(.subheadline)
}
}
.onAppear {
weatherFetcher.fetchWeathers() // Try BreakPoint
print("Pass")
}
}
I tried make breakpoint. However, the compiler passed the pew during debugging.
I also checked using print, but "Pass" did not appear in the console window.
Isn’t the onAppear function running before the List appears?
2
Answers
The key point lorem ipsum is making is that this line is evaluated before onAppear:
Then, if
onAppear
causes a@State
value to be changed (or a@Published
property that is being observed), then the body will be reevaluated.You must handle the case where
weathers
is empty.Presumably
weatherFetcher.fetchWeathers()
is an asynchronous call to retrieve some model data. The desired behavior is that when the user navigates to this view, the weather data is loaded and displayed. This means that you will need to add some empty state to display while the weather data is being fetched, such as a loader with a message.Your
body
logic should account for this by having a branch for whenweatherFetcher.weathers
is empty/nil. In that case, an empty state view will displayed instead of the List. Once the view appears (initially displaying the empty state), the weather data will load and populateweatherFetcher.weathers
, which property should be published by theweatherFetcher
class. The view will then respond to the published change and redraw, with thebody
logic displaying the list now thatweathers
is no longer nil.