-1

I have a notificationData @State property in my first view, and the values of this property are being set by the third subview when the user clicks on the list of notifications. After setting the value, I want to call a function to perform navigation. I have tried two ways to do this:

  1. Using .onChange(of:) - onChange requires conforming to Equatable so it only works when the user clicks on a different notification. I want to trigger the function whenever notificationData @State property is set, not only on change.

  2. Using @State + didSet - As the property itself is the State property wrapper didSet never gets called.

What would be the correct way to trigger the function whenever the state property is set, and not only on change?

I attempted to use the .onChange(of:) method, but it did not work as I intended. The method only fires when the value of the property changes, but I want it to be triggered every time the property is set.

For example, I have a list of notifications that includes two types: validity expiration and discount notifications. When a user clicks on the validity expiration notification, I set the notificationData for that notification, which triggers the method for the first time. However, if the user clicks on the same notification again, it does not trigger the onChange method for the second time. How can I make sure the method is triggered every time even when the same data is being set?"

  • `@State` works best for value types not for reference types. Reference types should be `ObservableObject`s and wrapped accordingly. Once you listen correctly `onChange` and `didSet` will work. – lorem ipsum Apr 20 '23 at 10:53

2 Answers2

0

You need to bind the navigation to the state that you set from the button. You can use .navigationDestination for this. SwiftUI generates the UI changes from the state, we don't need to call any functions.

malhal
  • 26,330
  • 7
  • 115
  • 133
-1

You can try manually publishing the changes like this:

class CustomViewModel: ObservableObject {
    var valueToObserve: Int = 0 {
        willSet {
            objectWillChange.send()
        }
    }
}
Matias Contreras
  • 442
  • 5
  • 10