Refreshing view by changing @State variable in SwiftUI not working

Viewed 586

so for simplicity sake, I am going to first describe the way my code functions. I have a List that is generated by using a ForEach loop to walk through an AWS database.

List{
    ForEach(self.data.database1){ row in
         HStack {
              Button("\((row.name)!)") { 
                   self.selectedItem = row.id
                   self.selectedItemName = row.poi!
                   self.pressedItem = true
                                
              }
                            
              Spacer()
              Button("Delete") {
                  self.selectedItem = row.id
                  self.showDeleteItemView = true
          //this brings up a view that can confirm you want to delete
              }.buttonStyle(BorderlessButtonStyle())                        
                        }
                    }
                    
                }

Each row in the list contains a "Delete" button. This delete button opens the view seen below:

if self.showDeleteEventView == true {
    ConfirmActionView(showView: self.$showDeleteItemView, actionName: "delete this event", function: {
              
                    for item in self.data.database1{
                        if self.selectedItem == item.id{
                            DispatchQueue.main.async {
                                self.data.deleteItem(id: event.id)
                                self.reloadView.toggle()
                            }
                        }
                    }
               
            }, buttonLabel: "Delete")
        }

The view is:

struct ConfirmActionView: View {
@Binding var showView: Bool
var actionName: String
var function: () -> Void
var buttonLabel: String
var body: some View {
    ZStack {
         VStack {
                HStack {
                    Spacer()
                    Button("X") {
                        self.showView = false
                    }
                }
                Text("Are you sure you want to \(self.actionName)?")
                    
                Spacer()
                HStack {
                    Button("\(self.buttonLabel)") {
                        print("confirmed action")
                        self.function()
                        self.showView = false
                    }
                   
                    
                    Button("Cancel") {
                        self.showView = false
                    }
                    .padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6))
                    
                }
                    
            }.frame(width: 300, height: 150)
            }
    }
}

The deleteItem() function is the following:

func deleteItem(id: Int) {
    let baseUrl = URL(string: itemUrl)
    let deletionUrl = baseUrl!.appendingPathComponent("\(id)")
    print("Deletion URL with appended id: \(deletionUrl.absoluteString)")

    var request = URLRequest(url: deletionUrl)
    request.httpMethod = "DELETE"
    print(token) // ensure this is correct
    request.allHTTPHeaderFields = ["Authorization": "Token \(token)"]
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Encountered network error: \(error)")
            return
        }
        
        if let httpResponse = response as? HTTPURLResponse {
            // this is basically also debugging code
            print("Endpoint responded with status: \(httpResponse.statusCode)")
            print("                   with headers:\n\(httpResponse.allHeaderFields)")
        }
        // Debug output of the data:
        if let data = data {
            let payloadAsSimpleString = String(data: data, encoding: .utf8) ?? "(can't parse payload)"
            print("Response contains payload\n\(payloadAsSimpleString)")
        }
    }
    task.resume()
}

stateVariable1 is the variable used to hold the name of the item in the row. reloadView is a @State Boolean variable and so I thought if I toggle it, the view should refresh after the item is deleted from the database. The code functions as I imagine EXCEPT the reloadView toggle doesn't actually reload the view.

1 Answers

You need a dynamic variant of ForEach if your data can change.

Try replacing:

List {
    ForEach(self.data.database1) { row in
         HStack {
             ...

with:

List {
    ForEach(self.data.database1, id: \.id) { row in
         HStack {
             ...

EDIT

It also looks like your data is not refreshed after you delete an item - you delete it from the server, but not locally.

You can reload it after you delete an item:

func deleteItem(id: Int) {
    ...
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        ...
        if let data = data {
            let payloadAsSimpleString = String(data: data, encoding: .utf8) ?? "(can't parse payload)"
            print("Response contains payload\n\(payloadAsSimpleString)")
        }

        // here you can reload data from the server
        // or pass function (which reloads data) as a parameter and call it here
    }
    task.resume()
}
Related