Issue with NavigationLink ID in List

Viewed 240

I'm trying to enable the edit functionality for list using a NavigationLink. I have the following:

EditView - want to use this view to edit the list items:

import SwiftUI
import Combine

struct EditView: View {
  @Binding var index: String
  @EnvironmentObject var taskStore: TaskStore
    var body: some View {
        Text("Hello, World!")
    }
}

struct EditView_Previews: PreviewProvider {
    @State static var index = ""
    static let taskStore = TaskStore()
    static var previews: some View {
        EditView(index: $index)
    }
}

And the list that should use the NavigationLink to edit the item:

if(self.taskStore.tasks.count != 0){
                List {
                    ForEach(self.taskStore.tasks) {
                        task in
                        NavigationLink(destination: EditView(index: task.$id)){
                        VStack(alignment: .leading, spacing: 0){
                                HStack{
                                    VStack{
                                        Text(task.description)
                                        .font(.headline)
                                            Text(String(task.outputYears) + "YRS" + String(task.outputMonths) + "MTHS")
                                        Spacer()
                                    }
                                }
                            }
                        }
                    }
                    .onDelete(perform: self.onDelete)
                }
                .navigationBarTitle("Menu")
                .listStyle(PlainListStyle())
                .padding(.top, 5)
            }

This line seem to be the issue:

NavigationLink(destination: EditView(index: task.$id))

How do I pass the task id to the EditView to enable me to edit the right time in the task store?

1 Answers

You don't need binding for index in this case - just pass it as value

struct EditView: View {
  var index: String        // << here !!
//...
}

and

NavigationLink(destination: EditView(index: task.id)){   // << here !!
Related