Search code examples
swiftuinsfetchrequest

SwiftUI - how to get newly created object to navigation link


I have a form that saves a new customer when a trailing navigation bar button labeled "Save" is pressed. I would then like to load a new view based on the new customer object. One possible way might be to activate a navigation link with an empty view like this:

NavigationLink(destination: CustomerDetailView(customer: currentCustomer), isActive: self.$showCustomerDetail) { EmptyView() }

Setting showCustomerDetail to true would make trigger the link. But to get a value for currentCustomer I'd need a dynamic fetch request, probably using the new UUID as a predicate. And that's where things fall apart. I can't figure out how to get the result of the fetch request to the currentCustomer variable.

Here are the useful parts of the code:

Navigation Bar Buttons

.navigationBarItems(leading:
   Button(action: {
      self.presentationMode.wrappedValue.dismiss()
   }, label: {
      Text("Cancel")
   }), trailing:
      Button(action: {
         let newCustomer = Customer(context: self.moc)
            newCustomer.id = UUID()
            newCustomer.custName = self.name
      }
      self.appDelegate.saveContext()
      self.showCustomerDetail = true
   })
}, label: {
   Text("Save")
})

Fetch Request

currentCustomer = FetchRequest<Customer>(entity: Customer.entity(), sortDescriptors: [], predicate: NSPredicate(format: "id == %@", custID as CVarArg))

Solution

  • Here is appropriate approach (as newCustomer is already saved into database it can be just used):

    .navigationBarItems(leading:
       Button(action: {
          self.presentationMode.wrappedValue.dismiss()
       }, label: {
          Text("Cancel")
       }), trailing:
          Button(action: {
             let newCustomer = Customer(context: self.moc)
                newCustomer.id = UUID()
                newCustomer.custName = self.name
          }
          self.appDelegate.saveContext()
    
          self.currentCustomer = newCustomer       // << here !!
          self.showCustomerDetail = true
       })
    }, label: {
       Text("Save")
    })