在列表中显示数据库查询结果 - SwiftUI & Supabase

Displaying results of database query in list - SwiftUI & Supabase

我正在尝试使用 Supabase 和 SwiftUI 作为 Firebase 的替代品。我在我的 Supabase 数据库中设置了一个 table,我的代码正在识别它并检索数据,但是一旦检索到它,我就无法在列表中显示它。

我可以将数据打印到控制台 window 以显示它实际上已被检索,但 List 似乎没有在模拟器屏幕上显示任何内容。

我的视图模型包含以下代码:

let client = SupabaseClient(supabaseUrl: SupabaseURL, supabaseKey: SupabaseKey)
@Published var todos: [Todo] = []    

// Retrieve all todo's
func getAllTodos() {
    print("Retrieving all todo's from database")
    
    let query = client.database.from("todos")
        .select()
    
    query.execute { results in
        switch results {
            case let .success(response):
                let todos = try? response.decoded(to: [Todo].self)
                self.todos = todos!
                print("Todos: \(todos)")
            case let .failure(error):
                print(error.localizedDescription)
        }
    }
    
}

我的 ContentView 包含此代码:

@State private var model = ContentViewModel()
@State var title = ""
@State var description = ""

var body: some View {
    VStack {
        TextField("Title", text: $title)
            .padding(5)
            .border(Color.black)
        TextField("Description", text: $description)
            .padding(5)
            .border(Color.black)
        Button("Create Todo") {
            model.createTodo(title: title, description: description)
        }
        .padding(10)
        Button("List todo's") {
            model.getAllTodos()
        }
        .padding(10)
        
        List(model.todos) { todo in
            Text("\(todo.title): \(todo.description)")
            Text("Done: \(String(describing: todo.isDone))")
        }
        .refreshable {
            model.getAllTodos()
        }
    }
    .padding(20)
    .onAppear {
        model.getAllTodos()
    }
    
}

如果我 运行 模拟器,并单击“列出待办事项”一次,控制台会显示以下输出:

Retrieving all todo's from database
2022-01-30 17:59:19.077191+0000 Supabase API 2[36461:1087300] [boringssl] boringssl_metrics_log_metric_block_invoke(151) Failed to log metrics
Todos: [Supabase_API_2.Todo(id: "56e81c25-2fbe-45da-ac57-5e0d92fdd9b4", title: "First Todo", description: "basic description", isDone: false), Supabase_API_2.Todo(id: "06b8e7bf-f990-4553-9c92-5a12a38d8e78", title: "Second todo", description: "another basic description", isDone: false)]
Retrieving all todo's from database
Todos: [Supabase_API_2.Todo(id: "56e81c25-2fbe-45da-ac57-5e0d92fdd9b4", title: "First Todo", description: "basic description", isDone: false), Supabase_API_2.Todo(id: "06b8e7bf-f990-4553-9c92-5a12a38d8e78", title: "Second todo", description: "another basic description", isDone: false)]

您可以看到它在加载视图时检索待办事项,然后在我单击“列出待办事项”按钮时再次检索。所以我可以看到它正在正确检索数据并存储在 'todos' var 中,但由于某种原因不会在列表中显示它。

如有任何帮助,我们将不胜感激!

假设 ContentViewModel 是一个 ObservableObject(它应该是),它应该用 @StateObject 注释(这是允许 View 连接到对象发布者),而不是 @State