I tried putting the check after the request
Seems you put the check after initializing FetchRequest, not after the request.
It is hard to predict when exactly the request is made or when the result is updated.
One possible solution would be like this:
struct TestViewPage: View {
var lodgeid: Int
@Environment(\.managedObjectContext) var managedObjectContext
var lodge: Lodge = getLodgeData()
var favourite: Bool {!cdlodges.isEmpty} //<-
//this gets the list
@FetchRequest var cdlodges: FetchedResults<CDLodge>
init(lodgeid: Int) {
self.lodgeid = lodgeid
self._cdlodges = FetchRequest(
entity: CDLodge.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \CDLodge.lodge, ascending: true),
],
predicate: NSPredicate(format: "lodgeid == \(lodgeid)")
)
}
var body: some View {
NavigationView {
ScrollView {
VStack(alignment: .leading) {
VStack {
switch favourite {
case false:
Button(action: {
///save the lodge in core data
//...
})
{
Image("favicon_off")
}
case true:
Button(action: {
///delete the lodge from Core Data
//...
})
{
Image("favicon_on")
}
}
}
}
.padding()
}///end of scrollview
.navigationBarTitle("")
.navigationBarHidden(true)
} //end of navigationview
}
}
With checking favourite dynamically, you would get the result you want.
(Though, I omitted favourite = setFav(), which I cannot guess what you want to do with it...)