首页 > 解决方案 > 如何在 perform(mutation: GraphQLMutation) 函数中重新加载 tableView 数据?

问题描述

我有一个应用程序,它使用 GraphQL 和 apollo 框架来显示一个带有国家列表的 tableView。我有一个工具栏按钮,单击该按钮时会显示一个警报对话框,允许用户输入国家/地区名称,以便将其添加到 AWS 上的数据库中。问题是在 perform(mutation: GraphQLMutation) 函数中,我无法获取我的数据并重新加载我的 tableView 以立即显示我的更改。不过,我可以使用单独的栏按钮获取我的列表。

我已经尝试过查看文档并逐步执行程序,但似乎在 perform(mutation: GraphQLMutation) 函数中调用 fetch 函数和 reload 函数过早,因为当 tableView 重新加载时,国家/地区计数低于实际数据库中的国家数量。例如,添加国家时,countriesCount 将是 30 而不是 31。所以当 tableView 重新加载时,它会在添加新国家之前重新加载。

let action = UIAlertAction(title: "Add Country", style: .default) { (action) in

        if let newCountry = textField.text {
            let addCountryMutation = AddCountryMutation(name: newCountry)
            self.apollo.perform(mutation: addCountryMutation) { (result, error) in
                self.fetchQueryResults()
                print("Country Added")
            }
        }

}

extension FetchCountryTableVC {

    func fetchQueryResults() {
        apollo.fetch(query: countriesQuery) { (result, error) in

            if let countries = result?.data?.countries.count {
                self.countriesCount = countries
            }

            self.tableView.reloadData()
        }
    }

}

我希望在执行突变后 fetchQueryResults() 函数将运行,获取国家计数并重新加载 tableView,以便国家列表将显示新添加的国家。

实际发生的是 tableView 重新加载而不显示更新的数据。

标签: iosswiftgraphqlapollo

解决方案


推荐阅读