The issue is likely in how you're using .task and @StateObject. Here are a few observations and potential solutions:
-
.task modifier will trigger the load() method every time the view appears. This means each time you navigate to this view, it will reload all data.
-
@StateObject creates a new instance of the view model every time the view is created, which also contributes to reloading.
Here are some potential solutions:
Solution 1: Use .onAppear with a check
.onAppear {
if cvm.charts.isEmpty {
Task {
await cvm.load()
}
}
}
This will only load data if the charts are empty, preventing unnecessary reloads.
Solution 2: Use .task(id:) to control when loading occurs
.task(id: someUniqueIdentifier) {
await cvm.load()
}
Solution 3: Consider using @ObservedObject instead of @StateObject
If the view model is created elsewhere and passed in, use @ObservedObject:
@ObservedObject var cvm: LatestVisualisationChartViewModel
Solution 4: Implement caching in the view model
Modify your view model to cache data and only reload if needed:
func load() async {
if charts.isEmpty {
// Perform network/data loading
}
}
Without seeing your LatestVisualisationChartViewModel, I can't be 100% certain, but the .task modifier is likely the primary cause of repeated reloading. The .task modifier runs the async task every time the view appears, which means every navigation to this view will trigger a reload.
Would you like me to elaborate on any of these solutions or provide more specific guidance?