"Modifying State during view update" warning from changing the placeholder in a TextField

Viewed 40

I have a textfield that I want to use to track tasks with in a MacOS App. As the placeholder, I would like to see the currently active task.

This means, I want to update the placeholder when the Task changes. When there is text in the Textfield when that happens, it works fine but when the Textfield is empty, and I change the placeholder, I get the warning

Modifying state during view update, this will cause undefined behaviour.

Now my main question is, is what I am doing not intended / bad practice or is that an oversight in SwiftUI?

Here is a code example for reproduction, I used the structure with two files because that's how it appeared in my App.

The view making the changes:

struct ContentView: View {
    @State var placeholder: String = "Test"

    var body: some View {
        VStack {
            SubView(placeholder: placeholder)
            Button("UpdatePlaceholder") {
                placeholder = placeholder == "Test" ? "Blub" : "Test"
            }
        }
    }
}

The subview that has the textfield with placeholder:

struct SubView: View {
    @State var currentText: String = ""
    let placeholder: String

    var body: some View {
        TextField(placeholder, text: $currentText)
    }
}

Pressing the button causes the same warning to appear when the TextField is empty.

I'm on Xcode 13.3.1 and MacOS 12.3.1

0 Answers
Related