0

I'm learning SwiftUI and I'm trying to build a simple To-Do app.

My root view is this:

struct ContentView: View {
    @State var reminders: [Reminder] = []
    
    var body: some View {
        print("ContentView", reminders)
        return VStack {
            RemindersListView(
                reminders: reminders
            )
            Button("Add") {
                reminders.append(.empty)
            }
        }
    }
}

And RemindersListView is

struct RemindersListView: View {
    @State var reminders: [Reminder]
    
    var body: some View {
        print("RemindersListView", reminders)
        return List {
            ForEach(reminders.indices) { index in
                ReminderView(reminder: $reminders[index])
            }
        }
    }
}

When I tap the Add button I get the following output:

ContentView []
RemindersListView []
ContentView [Common.Reminder(id: 2FC19F91-9B96-40DB-8CCB-4CBB39C62DBD, done: false, text: "")]
RemindersListView []

Meaning the state in ContentView changed and it re-renders the app, but RemindersListView receives the initial value.

Any ideas? Thanks

4
  • 1
    Use Binding instead of State in RemindersListView Commented Aug 23, 2021 at 13:19
  • Btw, no need for the return Commented Aug 23, 2021 at 14:15
  • @aheze: "Btw, no need for the return" yes but maybe he want check something with print. Commented Aug 23, 2021 at 14:30
  • @swiftPunk good point. Commented Aug 23, 2021 at 14:31

1 Answer 1

1

You are initializing the RemindersListView with an empty Array! then you are modifying it without updating it! You should Bind your data for solving the issue with @Binding, it is easiest way for you but not the only way to bind data, there are more ways to bind data.

struct RemindersListView: View {

    @Binding var reminders: [Reminder] // <<: Here!
    
    var body: some View {

        print("RemindersListView", reminders)

        return List {
            ForEach(reminders.indices) { index in
                ReminderView(reminder: $reminders[index])
            }
        }
    }
}

And also this in :

struct ContentView: View {
    @State var reminders: [Reminder] = []
    
    var body: some View {
        print("ContentView", reminders)
        return VStack {

            RemindersListView(reminders: $reminders) // <<: Here! with $

            Button("Add") {
                reminders.append(.empty)
            }

        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.