Skip to content

Storing previous results of a query in SwiftUI view #10

@mwildehahn

Description

@mwildehahn

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions