iOS SDK - Paginating search results

Yandas_Music1
Excursionist
59 0 5

Hello - I'm currently attempting to create code that would allow me to paginate through search results from the following base graphQL query:

static func searchForProducts(searchString:String, after cursor: String? = nil) -> Storefront.QueryRootQuery {
    Storefront.buildQuery { $0
        .shop { $0
            .products(first:20, after:cursor, query: searchString) { $0
                .fragmentForStandardProduct()
            }
        }
    }
}

Once pagination has been called, the following code is executed:

func collectionViewWillBeginPaging(_ collectionView: StorefrontCollectionView) {
        if let products = self.products,
            let lastProduct = products.items.last {
                Client.shared.searchProducts(searchString: processedString, after: lastProduct.cursor) { (products) in
                    if let products = products {
                        self.products.appendPage(from: products)
                        self.collectionView.completePaging()
                        self.collectionView.reloadData()
                    }
                }
        }
    }

Here is the code for searchProducts()

@discardableResult
    func searchProducts(searchString:String, after cursor: String? = nil, completion: @escaping (PageableArray<ProductViewModel>?) -> Void) -> Task {
        let query = ClientQuery.searchForProducts(searchString: searchString, sortKey: sortKey)
        let task = self.client.queryGraphWith(query) { (query, error) in
            error.debugPrint()
            if let query = query {
                let products = PageableArray(
                    with:     query.shop.products.edges,
                    pageInfo: query.shop.products.pageInfo
                )
                completion(products)
            } else {
                print("Failed to load products")
                completion(nil)
            }
        }
        task.resume()
        return task
    }

The above code is calling pagination, but instead of querying the products after .lastProduct, it simply starts the search back at the beginning. The result is an infiniately paginated product list that loops through the same 20 products over and over.

So obviously there is a flaw in my logic. I tried to apply the same pagination code that was found in the SDK for paginating through a collection, which is not working.

Any ideas? Thanks.

Replies 2 (2)
Dima_Bart
Shopify Staff (Retired)
Shopify Staff (Retired)
74 0 8

Your call to "ClientQuery.searchForProducts" is missing the "cursor" parameter. Your search is requesting the same page of products, over and over again.

Yandas_Music1
Excursionist
59 0 5

Nice catch Dima! Thanks a ton!

I would have stared at that for 10 more hours and not found the issue.

Alex