Relay.swift icon indicating copy to clipboard operation
Relay.swift copied to clipboard

Storing previous results of a query in SwiftUI view

Open mwildehahn opened this issue 5 years ago • 3 comments

I have a view with a search bar and a query to fetch the results. It all works great, but I'd like to store the previous results so that when you type, you don't jump into the "loading" state as the query executes.

I was trying something like this:

struct HomeView: View {
    @Query<HomeViewQuery>(fetchPolicy: .storeOrNetwork) private var query
    let searchQuery: String
    @State private var previousHits: [HomeViewQuery.Data.SearchResponse_search.SearchHit_hits]?
    
    func getResults() -> Query<HomeViewQuery>.Result {
        switch query.get(.init(query: searchQuery)) {
        case .loading:
            return .loading
        case .failure(let error):
            return .failure(error)
        case .success(let data):
            if let hits = data?.search?.hits {
                print("Setting previous hits: \(hits)")
                previousHits = hits
            }
            
            return .success(data)
        }
    }

    var body: some View {
        Group {
            if !searchQuery.isEmpty {
                switch getResults() {
                case .loading:
                    Group {
                        if previousHits != nil {
                            SearchResults(hits: previousHits!)
                        } else {
                            Text("Loading...")
                        }
                    }
                case .failure(let error):
                    Text("Error: \(error.localizedDescription)")
                case .success(let data):
                    if data?.search?.hits != nil && (data?.search?.nbHits ?? 0) > 0 {
                        SearchResults(hits: data!.search!.hits!)
                    } else {
                        Text("No results")
                    }
                }
            } else {
                Text("Search for stuff")
            }
        }
    }

But then get an error about modifying state during view update and the UI hangs when typing. Is it possible to subscribe to the query results in some way to do this or given this custom behavior, should I just directly call fetchQuery?

mwildehahn avatar Dec 31 '20 09:12 mwildehahn