How do I get updated custom EnvironmentValues after a method call?

I have a custom EnvironmentVariable called analyticsData. On the button tap, I want to perform my button's action and then call a method to send this data.

struct PrimaryButton: View {
    @Environment(\.analyticsData) private var analyticsData

    private let title: String
    private let action: (() -> Void)

    init(_ title: String, action: @escaping (() -> Void)) {
        self.title = title
        self.action = action
    }

    var body: some View {
        Button(action: handleTap) {
            Text(title)
        }
    }

    func handleTap() {
        action()
        // need updated value of analyticsData here!
        AnalyticsProxy.shared.sendAnalytics(analyticsData)
    }
}

At the point of use for this PrimaryButton, I would like to update my data dynamically. However, tapping between my 2 buttons, the data is 1 click behind.

  • button 1 tapped, analytics output: buttonTapped = ""
  • button 2 tapped, analytics output: buttonTapped = "B1"
  • button 1 tapped, analytics output: buttonTapped = "B2"

In my PrimaryButton handleTap method (above), I need to get the updated value of the environmentVariable before sending the analytics. Is this possible?

Point of use:

struct ContentView: View {
    @State var buttonTapped = ""

    var body: some View {
        VStack(spacing: 64) {
            PrimaryButton("Button 1") {
                buttonTapped = "B1"
            }.analytics(type: .event, name: "Button Tap", data: ["Button": buttonTapped])

            PrimaryButton("Button 2") {
                buttonTapped = "B2"
            }.analytics(type: .event, name: "Button Tap", data: ["Button": buttonTapped])
        }
    }
}

  • I know how to do it statically. The data shown here was for illustrative purposes. What if I have a form and want to send some user-entered form data? Or the new state of a toggle after the user flips it? If I can't, I can take another approach. I was just wondering if there's a way in my implementation. 

Add a Comment

Replies

...